简体   繁体   中英

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.

  1. For each "item" in the meal_recipe, check if item is in pantry.
  2. If yes, check if "value" of meal_recipe is more than pantry. If yes add key + difference in value in shopping_list.
  3. If no, add both Key & value of meal_recipe to 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:

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 . The key is item . So you should use pantry[item] , not 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. 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.

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:

shopping_list[ingredient] = shopping_list.get(ingredient, 0) + qty_needed - qty_in_pantry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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