You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python字典中的值按对应关系两两配对打印?

解决方法

你原来的代码是遍历字典所有键,每个值单独打印一行,自然会每个值占一行。要实现成对输出,可按以下方式实现:

方法1:按键名规则匹配(兼容性最好,不受字典顺序影响)

你的字典key有明确的编号对应规则,直接按编号匹配食材和对应分量即可:

data = {"Name": "salat "
, "Ingredient 1": "salad ", "Number of in1": 60
, "Ingredient 2": "salt ", "Number of in2": 19
, "Ingredient 3": "oil ", "Number of in3": 20
, "Ingredient 4": "cheese ", "Number of in4": 50
, "Ingredient 5": "pepper", "Number of in5": 10
}
# 先单独打印菜品名
print(data['Name'])
# 遍历1-5的序号,匹配对应的食材和数量输出
for idx in range(1, 6):
    ingredient = data[f'Ingredient {idx}']
    count = data[f'Number of in{idx}']
    # 如果你不需要食材名末尾的空格,可以加.strip(),不需要就去掉这个方法
    print(f"{ingredient.strip()} {count}")

方法2:按字典值顺序分组输出(适用于Python3.7及以上版本,默认保留字典插入顺序)

如果不想硬编码key规则,可以把字典值转成列表后,第一个值单独打印,后续每两个为一组输出:

data = {"Name": "salat "
, "Ingredient 1": "salad ", "Number of in1": 60
, "Ingredient 2": "salt ", "Number of in2": 19
, "Ingredient 3": "oil ", "Number of in3": 20
, "Ingredient 4": "cheese ", "Number of in4": 50
, "Ingredient 5": "pepper", "Number of in5": 10
}
value_list = list(data.values())
# 打印第一个元素:菜品名
print(value_list[0])
# 从第二个元素开始,每两个为一组遍历
for i in range(1, len(value_list), 2):
    ingredient = value_list[i]
    count = value_list[i+1]
    print(f"{ingredient.strip()} {count}")

两种方法运行后都可以得到你期望的输出结果。

内容的提问来源于stack exchange,提问作者Steve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:45:03