簡體   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