[英]Python program to combine two dictionary adding values for common keys
I have two dictionaries and I need to combine them. 我有两个字典,需要将它们结合起来。 I need to sum the values of similar keys and the different keys leave them without sum. 我需要对相似键的值求和,而不同的键使它们不求和。
These are the two dictionaries: 这是两个字典:
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
The expected results: 预期结果:
d3= {'b': 400, 'd': 400, 'a': 400, 'c': 300}
I have successfully made the sum and added them to this third dictionary, but I couldn't know, how to add the different values. 我已经成功地将总和添加到了第三本字典中,但是我不知道如何添加不同的值。
My try 我的尝试
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d3 = {}
for i, j in d1.items():
for x, y in d2.items():
if i == x:
d3[i]=(j+y)
print(d3)
My results = {'a': 400, 'b': 400}
Version without collections.Counter
: 没有collections.Counter
版本:
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = {k: d1.get(k, 0) + d2.get(k, 0) for k in d1.keys() | d2.keys()}
print(d)
Prints: 打印:
{'b': 400, 'c': 300, 'd': 400, 'a': 400}
EDIT: With for
-loop: 编辑:与for
循环:
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = {}
for k in d1.keys() | d2.keys():
d[k] = d1.get(k, 0) + d2.get(k, 0)
print(d)
collections.Counter
does what you need: collections.Counter
可以满足您的需求:
from collections import Counter
d1 = {"a": 100, "b": 200, "c": 300}
d2 = {"a": 300, "b": 200, "d": 400}
d3 = Counter(d1) + Counter(d2)
# Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
I like Andrej's answer (I LOVE list/dict comprehensions), but here's yet another thing: 我喜欢安德烈(Andrej)的回答(我喜欢列表/字典的理解),但这又是另一回事:
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d3 = dict(d1) # don't do `d3=d1`, you need to make a copy
d3.update(d2)
for i, j in d1.items():
for x, y in d2.items():
if i == x:
d3[i]=(j+y)
print(d3)
I realised your own code can be "fixed" by first copying values from d1 and d2. 我意识到可以通过首先从d1和d2复制值来“修复”您自己的代码。
d3.update(d2)
adds d2's contents to d3, but it overwrites values for common keys. d3.update(d2)
将d2的内容添加到d3中,但是它将覆盖公用密钥的值。 (Making d3's contents {'a':300, 'b':200, 'c':300, 'd':400}
) (使d3的内容{'a':300, 'b':200, 'c':300, 'd':400}
)
However, by using your loop after that, we correct those common values by assigning them the sum. 但是,此后通过使用循环,我们可以通过分配总和来更正这些公共值。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.