Python迭代父字典时如何跳过嵌套字典?菜单场景问题解析
解决Python字典遍历中跳过嵌套字典的问题
问题说明
想要获取饮品菜单字典里各饮品的名称和对应价格,但当前遍历代码会把嵌套的ingredients字典也一起输出,如何修改才能只显示饮品和价格?
原代码
menu = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": {'ingredients': { "water": 200, "milk": 150, "coffee": 24, }, 'cost': 2.5}, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } elif selection == "menu": print("Please choose your drink:\n") for drink in menu: for cost in menu[drink].values(): print(f"{drink.capitalize()}: ${cost}0")
原运行结果
Espresso: ${'water': 50, 'coffee': 18}0 Espresso: $1.50 Latte: ${'water': 200, 'milk': 150, 'coffee': 24}0 Latte: $2.50 Cappuccino: ${'water': 250, 'milk': 100, 'coffee': 24}0 Cappuccino: $3.00
解决方案
方法一:直接通过键访问cost值
既然每个饮品字典都有明确的cost键,完全不需要遍历所有值,直接取值即可,还能精准避免输出ingredients:
elif selection == "menu": print("Please choose your drink:\n") for drink_name, drink_details in menu.items(): # 用字符串格式化确保价格显示两位小数 print(f"{drink_name.capitalize()}: ${drink_details['cost']:.2f}")
运行结果:
Please choose your drink: Espresso: $1.50 Latte: $2.50 Cappuccino: $3.00
这里的.2f会自动处理小数位数,比手动拼接0更可靠,比如能把3.0转为3.00,1.5转为1.50。
方法二:遍历键值对时跳过ingredients
如果需要保留遍历逻辑,可通过判断键名筛选出cost字段:
elif selection == "menu": print("Please choose your drink:\n") for drink_name, drink_details in menu.items(): for key, value in drink_details.items(): if key == 'cost': print(f"{drink_name.capitalize()}: ${value:.2f}")
这个方法适合后续菜单新增其他需要展示的字段时,只需修改判断条件即可。
原代码出错原因
原代码中menu[drink].values()会返回该饮品下的所有值——包括ingredients对应的嵌套字典和cost对应的数值,遍历过程中会把两个值都输出,因此出现了打印字典的异常情况。
内容的提问来源于stack exchange,提问作者villebellez
相关产品推荐
相关产品推荐

