python 合并字典,相同 key 的 value 如何相加?

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))

 

posted on 2018-03-13 17:44  星河赵  阅读(17027)  评论(0编辑  收藏  举报

导航