python - 如何连接字典(值到相同键和新键的值)?

标签 python dictionary word-cloud textedit

<分区>

我在连接字典时遇到问题。有这么多代码,所以我用例子来说明我的问题是什么。

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

关于python - 如何连接字典(值到相同键和新键的值)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41048896/

相关文章:

python - Pandas:按行划分多索引数据帧

python - 将图转换为出度 1(额外的零权重边除外)

python - 将命令行参数传递给从 Makefile 调用的 python 脚本

java - 添加映射<String, Entity>时约束冲突合并实体

python - 如何将具有键值对的列表转换为字典

r - 创建词组而不是R中的单个词的 "word"云

CSS如何实现词云?

Python内部实体模拟

python - Pandas DataFrame 中的字典嵌套列表

javascript - 从elasticsearch创建wordcloud d3.js