如何将字典拼接在一起(将相同键的值拼接为新的键和值)?

2024-05-14 10:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个连接字典的问题。有这么多代码,所以我在示例中显示了我的问题所在。在

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准备字数。我不知道如何连接键的值这对我来说是个难题。请帮忙。 谨致问候


Tags: the代码示例字典wordd2d1d3
3条回答
import itertools

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}
dicts = [d1, d2, d3]

In [31]: answer = {k:sum(d[k] if k in d else 0 for d in dicts) for k in itertools.chain.from_iterable(dicts)}

In [32]: answer
Out[32]: 
{'sequel': 1,
 'the': 10,
 'fine': 16,
 'jimbo': 1,
 'word': 6,
 'orange': 1,
 'knight': 1}

我将使用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)

输出:

^{pr2}$
def sumDicts(*dicts):
    summed = {}
    for subdict in dicts:
        for (key, value) in subdict.items():
            summed[key] = summed.get(key, 0) + value
    return summed

外壳示例:

^{pr2}$

相关问题 更多 >

    热门问题