x = { 'apple': 1, 'banana': 2 }
y = { 'banana': 10, 'pear': 11 }

需要把两个字典合并,最后输出结果是:

{ 'apple': 1, 'banana': 12, 'pear': 11 }

 

利用collections.Counter可轻松办到

>>> x = { 'apple': 1, 'banana': 2 }
>>> y = { 'banana': 10, 'pear': 11 }
>>> from collections import Counter
>>> X,Y = Counter(x), Counter(y)
>>> z = dict(X+Y)
>>> z
>>>from collections import Counter
>>>dict(Counter(x)+Counter(y))

 

相关文章: