Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum value of two different dictionaries which is having same key

Tags:

python

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 .

like image 625
Prashant Gaur Avatar asked Dec 12 '22 10:12

Prashant Gaur


1 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 a true dict, just use dict(first_plus_second):

>>> print dict(first_plus_second)
{'age': 23, 'id': 5, 'out': 100}
like image 66
ron rothman Avatar answered Apr 08 '23 02:04

ron rothman