首页 > 解决方案 > 比较两个字典并将识别的键和值差异添加到新字典

问题描述

我有两本字典,我正在尝试使用 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

有人可以告诉我应该怎么做吗?

标签: pythonpandasloopsdictionary

解决方案


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

推荐阅读