我有两个字典,我正在尝试使用For循环混合If条件来实现以下功能
meal_recipe = {'pasta': 2, 'garlic': 2, 'sauce': 3,
'basil': 4, 'salt': 1, 'pepper': 2,
'olive oil': 2, 'onions': 2, 'mushrooms': 6}
pantry = {'pasta': 3, 'garlic': 4,'sauce': 2,
'basil': 2, 'salt': 3, 'olive oil': 3,
'rice': 3, 'bread': 3, 'peanut butter': 1,
'flour': 1, 'eggs': 1, 'onions': 1, 'mushrooms': 3,
'broccoli': 2, 'butter': 2,'pickles': 6, 'milk': 2,
'chia seeds': 5}
我是python的noob,所以到目前为止,我一直坚持下面的代码,不知道如何继续:
for item, stock in meal_recipe.items():
if item in pantry:
if mean_recipe [stock] > pantry [stock]: ????? Not sure
Shopping_list={item for item in mean_recipe} ????? Not sure
有人能告诉我怎么做吗
stock
不是字典键,它是来自meal_recipe
的值。关键是item
。所以你应该使用pantry[item]
,而不是pantry[stock]
您可以使用
dict.get()
方法来指定默认值,而不是显式检查该项是否在字典中。这样,您可以将字典中不存在的项视为数量为0,这将始终小于您需要的数量如果购物清单中可能已经有商品,并且您可能希望增加购买数量,那么您也可以在那里使用
.get()
:相关问题 更多 >
编程相关推荐