Python两个字典如何相加

2020-02-26  本文已影响0人  只言片语谁知

两个字典具有部分相同的key,相同key对应的value如何相加呢?
方法一:字典的循环

dict1={'torch':6,'gold coin':42}
dict2={'rope':1,'gold coin':20}
for m, n in dict2.items():
    if m in dict1:
        dict1[m] += n
    else:
        dict1.setdefault(m, n)
print('dict1=',dict1)

结果为

dict1= {'torch': 6, 'gold coin': 62, 'rope': 1}

方法二:内置函数Counter

from collections import Counter
dict1={'torch':6,'gold coin':42}
dict2={'rope':1,'gold coin':20}
dict_new=dict(Counter(dict1)+Counter(dict2))
print(dict_new)
上一篇下一篇

猜你喜欢

热点阅读