我正在寻找一种 Pythonic 方式(尽可能少的代码)来统一两个字典的内容:
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
我想得到第三个篮子,它将成为其他两个篮子的“总和”,篮子 3 应该是:
basket3 --> {"ham":2,"eggs":7,"spam":1}
如果可能,请使用set
我正在寻找一种 Pythonic 方式(尽可能少的代码)来统一两个字典的内容:
basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}
我想得到第三个篮子,它将成为其他两个篮子的“总和”,篮子 3 应该是:
basket3 --> {"ham":2,"eggs":7,"spam":1}
如果可能,请使用set
我会使用 a 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}
由于您正在尝试计算值,请使用collections.Counter
:
basket3 = collections.Counter(basket1)
basket3.update(basket2)
或者:
basket3 = collections.Counter(basket1) + collections.Counter(basket2)
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}