0

Suppose:

dict1 = {'a': {'b': 2, 'c': 3}, 'd': 4}
dict2 = {'a': {'b': 1, 'd': 4}, 'c': 3}

Then merging both dict1 and dict2, I should get

{'a': {'b': 3, 'c': 3, 'd': 4}, 'c': 3, 'd': 4}

When both have same key, then add there values together , i.e., in this case for b : ( 2+1) (actually it could be integer or list).

Is there any pythonic way to do this. The only way that strikes to mind is to loop over all the keys and values, but I queries that there should be another way.

reetesh11
  • 661
  • 1
  • 9
  • 16
  • Well, from what I see you're adding the numbers when you have conflicting keys, I haven't found a way to merge dictionnaries this way (the usual 'update' method, uses the last dictionary values to update the 'merged dictionnary. – tglaria Nov 30 '15 at 13:25
  • Forget it: http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe – tglaria Nov 30 '15 at 13:27
  • usually 'update' is done, but in my case I need to add there respective values together. – reetesh11 Nov 30 '15 at 16:31
  • That's why: check my last comment. – tglaria Nov 30 '15 at 18:55

0 Answers0