首页 > 解决方案 > 使用 for/in 语句合并字典功能

问题描述

我是 Python 的初学者,所以我需要一个简单的解释。

我有两个字典:

supply_dictionarie = {'Apple': 20, 'Cigar': 100, 'Milk': 210, 'Flower': 75}

goods_dictionarie = {'Milk': 210, 'Apple': 50, 'WhiteWine': 200, 'Beer': 300, 'Oranges': 400}

我试图合并这两个字典,同时对重复键的值求和。我的目的是获得:

merged_dictionarie = {'Milk': 420, 'Cigar': 100, 'Apple': 70, 'WhiteWine': 200, 'Beer': 300, 'Oranges': 400, 'Flower': 75} *(not necessarily in this order)

我正在使用以下代码:

def merge_supply():
    for k in supply_dictionarie:
        if k in set(goods_dictionarie):
            merged_dictionarie[k] = goods_dictionarie.get(k, 0) + supply_dictionarie.get(k, 0)
        elif k not in set(goods_dictionarie):
            merged_dictionarie[k] = supply_dictionarie.get(k, 0)
        else:
            break
    for k in goods_dictionarie:
         if k not in set(supply_dictionarie):
            merged_dictionarie[k] = goods_dictionarie.get(k, 0)
         else:
            break

但我得到的只是:

merged_dictionarie = {'Apple': 70, 'Cigar': 100, 'Milk': 420, 'Flower': 75}

对我来说,这表明第二个“for/in”表达式没有成功执行工作。出了什么问题?

标签: pythondictionarymerge

解决方案


您可以使用以下方法简化循环:

>>> from collections import defaultdict
>>> merged = defaultdict(int)
>>> for i in supply_dictionarie :
...     merged[i] += supply_dictionarie[i]
... 
>>> for i in goods_dictionarie :
...     merged[i] += goods_dictionarie[i]
... 
>>> dict(merged)
{'Beer': 300, 'Flower': 75, 'Apple': 70, 'Cigar': 100, 'WhiteWine': 200, 'Oranges': 400, 'Milk': 420}

推荐阅读