python - 比较两个字典并将识别的键和值差异添加到新字典
问题描述
我有两本字典,我正在尝试使用 For 循环与 If 条件混合来实现以下目标。
- 对于 meal_recipe 中的每个“项目”,检查项目是否在储藏室中。
- 如果是,请检查meal_recipe 的“价值”是否超过食品储藏室。如果是,则在 shopping_list 中添加键 + 差值。
- 如果没有,将meal_recipe 的Key 和value 添加到shopping_list。
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中的菜鸟,所以到目前为止我一直停留在下面的代码中,不知道如何继续:
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,这将始终小于您需要的数量。
for ingredient, qty_needed in meal_recipe.items():
qty_in_pantry = pantry.get(ingredient, 0)
if qty_needed > qty_in_pantry:
shopping_list[ingredient] = qty_needed - qty_in_pantry
如果购物清单可能已经有商品并且您可能想增加购买数量,您也可以.get()
在那里使用:
shopping_list[ingredient] = shopping_list.get(ingredient, 0) + qty_needed - qty_in_pantry
推荐阅读
- python - 检查 DataFrame 中的前导零
- woocommerce - 在 Woocommerce 中删除订单摘要页面上的摘要
- python - 如何从字典值中提取字符串
- npm - 是否可以让 npm 从本地文件获取依赖项但回退到已发布的包?
- javascript - 修改预加载器以输出不同的字母
- python - 使用 python 子进程和 7-zip 提取 .tgz 文件
- iframe - 如何在访问或刷新页面时随机播放 YouTube 播放列表
- android - 如何在 google play 上制作没有“立即尝试”按钮的 Android Instant App?
- reactjs - 如何在 ReactNative 中添加到现有样式表。如何在样式表中使用扩展运算符?
- c++ - ONNX 网络能否与 onnxruntime 不兼容?