繁体   English   中英

比较两个字典并将识别的键和值差异添加到新字典

[英]Compare two dictionaries and add the identified key and difference in value to a new dict

我有两本字典,我正在尝试使用 For 循环与 If 条件混合来实现以下目标。

  1. 对于 meal_recipe 中的每个“项目”,检查项目是否在储藏室中。
  2. 如果是,请检查meal_recipe 的“价值”是否超过食品储藏室。 如果是,则在 shopping_list 中添加键 + 值差异。
  3. 如果没有,将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM