The value of the sum of two different dictionaries having the same key

I have two dictionaries

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

I want the output dictionary to be

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

I tried

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

but I get id as 4, but I want it to be 5.

+4
source share
3 answers

You want to use 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 true dict, just use dict(first_plus_second):

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

, :

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

:

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

You can simply update the key 'id'after this:

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

All Articles