4

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 .

Prashant Gaur
  • 8,712
  • 10
  • 47
  • 71
  • possible duplicate of [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) – Martijn Pieters Nov 09 '13 at 20:29

3 Answers3

13

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}
ron rothman
  • 16,048
  • 6
  • 38
  • 40
0

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}
piokuc
  • 24,264
  • 10
  • 66
  • 98
0

You can simply update the 'id' key afterwards:

result = dict(first.items() + second.items())
result['id'] = first['id'] + second['id']
Simeon Visser
  • 113,587
  • 18
  • 171
  • 175
  • thanks for your answer . if we do not know which key is same in all dictionary like there is very big dictinary . ?? thanks – Prashant Gaur Nov 09 '13 at 20:34