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