Python-将一本字典添加到另一本 [英] Python - add one dictionary to another
本文介绍了Python-将一本字典添加到另一本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用Python更新一个字典,但是如果有一些相同的参数,则应添加它们的值.例如:
I want to update one dictionary with another in Python, but if there are some same arguments, their values should be added. For example:
a = {"word_1" : 1, "word_2": 2}
b = {"word_2" : 5, "word_3": 7}
输出必须为:
{"word_1" : 1, "word_2": 7, "word_3": 7}
我在Google上搜索了很多,但是在大多数答案中,值都被重写了,我想添加它们这是我的解决方案:
I have googled a lot, but in most answers values rewrites, I want to add them Here is my solution:
for i in a.keys():
if i in b.keys():
b[i] += a[i]
else:
b[i] = a[i]
有没有最有效的方法?
推荐答案
Use a Counter
, which is a special kind of dictionary for counting objects.
from collections import Counter
a = Counter({"word_1" : 1, "word_2": 2})
b = Counter({"word_2" : 5, "word_3": 7})
print(a + b)
打印
Counter({'word_2': 7, 'word_3': 7, 'word_1': 1})
这篇关于Python-将一本字典添加到另一本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文