3

我正在寻找一种 Pythonic 方式(尽可能少的代码)来统一两个字典的内容:

basket1 = {"ham":2,"eggs":3}
basket2 = {"eggs":4,"spam":1}

我想得到第三个篮子,它将成为其他两个篮子的“总和”,篮子 3 应该是:

basket3 --> {"ham":2,"eggs":7,"spam":1}

如果可能,请使用set

4

3 回答 3

10

我会使用 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}
于 2012-12-27T21:04:02.440 回答
4

由于您正在尝试计算值,请使用collections.Counter

basket3 = collections.Counter(basket1)
basket3.update(basket2)

或者:

basket3 = collections.Counter(basket1) + collections.Counter(basket2)
于 2012-12-27T21:02:25.467 回答
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}
于 2012-12-27T21:06:01.060 回答