如何合并字典(将相同键的值合并成一个新的键对应的值)?

7
我在合并字典方面遇到了问题。由于代码很多,所以我将在示例中展示我的问题。
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}

正在为词云准备字数统计。我不知道如何连接键的值,这对我来说是一个难题。请帮助我。 最好的祝福


1
欢迎来到 [so]!请查看 [ask] 并展示您尝试过的内容! - TemporalWolf
3个回答

8
我会使用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})

计数器似乎可以解决很多字典问题!对于这个问题,我会使用reduce(lambda x,y:Counter(x)+Counter(y),[d1,d2, d3])。update()比添加计数器更快/更好吗? - themistoklik
@themistoklik 如果有的话,也不会太多,而且在Python 3中已经弃用了“reduce”方法。我最初是用“map(c.update, (d1, d2, d3))”来编写这段代码的,但是我的内部函数式编程者拒绝允许我滥用副作用。 - Patrick Haugh

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}

“knight”、“sequel”、“orange”和“jimbo”怎么样? - rassar
@InspectorGadget 做得好! - rassar
哇塞,谢谢你的好代码!这一行真是妙极了 :) - MTG
为什么要踩我? - inspectorG4dget

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}

if key in summed... would probably be better off as summed[key] = summed.get(key, 0) + value - Sean McSomething
@SeanMc,这在我的电脑上不起作用...显示“无法分配给函数调用”。 - rassar
抱歉,有些东西搞混了。已在编辑中修复。 - Sean McSomething
@SeanMcSomething 已修复! - rassar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接