如何连接dicts(值与同一键和新键的值)?

时间:2016-12-08 21:12:23

标签: 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预备wordcounts。我不知道如何连接键的值,这对我来说很困惑。请帮忙。 最好的问候

3 个答案:

答案 0 :(得分:5)

我会使用collections中的Counter进行此操作。

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

答案 1 :(得分:2)

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}

答案 2 :(得分:2)

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

Shell示例:

>>> 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}
>>> sumDicts(d1, d2, d3)
{'orange': 1, 'the': 10, 'fine': 16, 'jimbo': 1, 'word': 6, 'knight': 1, 'sequel': 1}