我正在寻找一种Pythonic方式(可能的代码越少)来统一两个词典的内容:
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
我希望得到第三个篮子,这将是另外两个篮子的总和,篮子3应该是:
basket3 --> {"ham":2,"eggs":7,"spam":1}
如果可能,请使用set
答案 0 :(得分:10)
我使用Counter
,这是一种具有一些不错属性的defaultdict
:
>>> from collections import Counter
>>> basket1 = {"ham":2,"eggs":3}
>>> basket2 = {"eggs":4,"spam":1}
>>> basket_sum = Counter(basket1) + Counter(basket2)
>>> basket_sum
Counter({'eggs': 7, 'ham': 2, 'spam': 1})
如果您愿意,可以将其转换回纯dict
:
>>> dict(basket_sum)
{'eggs': 7, 'ham': 2, 'spam': 1}
答案 1 :(得分:4)
由于您尝试计算值,请使用collections.Counter
:
basket3 = collections.Counter(basket1)
basket3.update(basket2)
或者:
basket3 = collections.Counter(basket1) + collections.Counter(basket2)
答案 2 :(得分:2)
In [2]: basket1 = {"ham":2,"eggs":3}
In [3]: basket2 = {"eggs":4,"spam":1}
In [4]: baskets = [basket1, basket2]
In [5]: answer = collections.defaultdict(int)
In [6]: for basket in baskets:
...: for item in basket:
...: answer[item] += basket[item]
...:
In [7]: answer
Out[7]: defaultdict(<type 'int'>, {'eggs': 7, 'ham': 2, 'spam': 1})
In [8]: dict(answer)
Out[8]: {'eggs': 7, 'ham': 2, 'spam': 1}