简体   繁体   English

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

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

I have two dictionary and I am trying to use a For loop mix with If conditional to achieve the following.我有两本字典,我正在尝试使用 For 循环与 If 条件混合来实现以下目标。

  1. For each "item" in the meal_recipe, check if item is in pantry.对于 meal_recipe 中的每个“项目”,检查项目是否在储藏室中。
  2. If yes, check if "value" of meal_recipe is more than pantry.如果是,请检查meal_recipe 的“价值”是否超过食品储藏室。 If yes add key + difference in value in shopping_list.如果是,则在 shopping_list 中添加键 + 值差异。
  3. If no, add both Key & value of meal_recipe to 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}

I am a noob in python so I got stuck to at the code below so far and not sure how to proceed:我是 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

Can someone show me how it should be done?有人可以告诉我应该怎么做吗?

stock is not a dictionary key, it's the value from meal_recipe . stock不是字典键,它是meal_recipe的值。 The key is item .关键是item So you should use pantry[item] , not pantry[stock] .所以你应该使用pantry[item] ,而不是pantry[stock]

Instead of checking explicitly whether the item is in the dictionary, you can use the dict.get() method, which allows you to specify a default value.您可以使用dict.get()方法,而不是显式检查该项目是否在字典中,该方法允许您指定默认值。 That way, you can treat an item that isn't in the dictionary as having quantity 0, which will always be less than the quantity you need.这样,您可以将不在字典中的项目视为数量为 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

If the shopping list could already have items and you might want to increase the quantity to buy, you can also use .get() there:如果购物清单可能已经有商品并且您可能想增加购买数量,您也可以在此处使用.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