简体   繁体   English

具有相同键的两个不同字典的总和值

[英]sum value of two different dictionaries which is having same key

i am having two dictionaries 我有两本词典

first = {'id': 1, 'age': 23}
second = {'id': 4, 'out': 100}

I want output dictionary as 我想要输出字典

{'id': 5, 'age': 23, 'out':100}

I tried 我试过了

>>> dict(first.items() + second.items())
{'age': 23, 'id': 4, 'out': 100}

but i am getting id as 4 but i want to it to be 5 . 但我得到的身份是4,但我希望它是5。

You want to use collections.Counter : 你想使用collections.Counter

from collections import Counter

first = Counter({'id': 1, 'age': 23})
second = Counter({'id': 4, 'out': 100})

first_plus_second = first + second
print first_plus_second

Output: 输出:

Counter({'out': 100, 'age': 23, 'id': 5})

And if you need the result as a true dict , just use dict(first_plus_second) : 如果您需要将结果作为真正的dict ,只需使用dict(first_plus_second)

>>> print dict(first_plus_second)
{'age': 23, 'id': 5, 'out': 100}

If you want to add values from the second to the first, you can do it like this: 如果要将值从第二个添加到第一个,可以这样做:

first = {'id': 1, 'age': 23}
second = {'id': 4, 'out': 100}

for k in second:
    if k in first:
        first[k] += second[k]
    else:
        first[k] = second[k]
print first

The above will output: 以上将输出:

{'age': 23, 'id': 5, 'out': 100}

You can simply update the 'id' key afterwards: 您可以稍后更新'id'键:

result = dict(first.items() + second.items())
result['id'] = first['id'] + second['id']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM