python合併字典的值

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

如果是大列表套小字典的格式

可以加一個循環

user_tag = [{'count':10,'tag':'喜劇'},{'count':5,'tag':'話劇'},{'count':3,'tag':'喜劇'}]
from collections import defaultdict

di_pair = defaultdict(int)
  # 定義字典的值爲int型
for di in user_tag:
    
    di_pair[di.get('tag')] += di.get('count')  # 向字典添加值

輸出:{'喜劇':13,'話劇':5}

總之很靈活的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章