我在连接字典时遇到问题。有这么多代码,所以我用例子来说明我的问题是什么。
d1 = {'the':3, 'fine':4, 'word':2}
+
d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
+
d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}
=
finald = {'the':10, 'fine':16, 'word':6, 'knight':1, 'orange':1, 'sequel':1, 'jimbo':1}
它正在为 wordcloud 准备字数统计。我不知道如何连接键的值,这对我来说很困惑。请帮忙。
最好的问候
我会使用 Counter
来自 collections
为此。
from collections import Counter
d1 = {'the':3, 'fine':4, 'word':2}
d2 = {'the':2, 'fine':4, 'word':1, 'knight':1, 'orange':1}
d3 = {'the':5, 'fine':8, 'word':3, 'sequel':1, 'jimbo':1}
c = Counter()
for d in (d1, d2, d3):
c.update(d)
print(c)
输出:
Counter({'fine': 16, 'the': 10, 'word': 6, 'orange': 1, 'jimbo': 1, 'sequel': 1, 'knight': 1})