0

So I realized that

dict1.update(dict2)

replaces values of dict2 with dict1 if the key exists in both the dictionaries. Is there any way to add the values of dict2 to dict1 directly if the key is present instead of looping around the key,value pairs

Gaurav
  • 617
  • 2
  • 9
  • 23
  • 1
    IF you don't want to replace the values in dict1, you could just do dict2.copy().update(dict1) and get what you want. – Antimony Aug 06 '12 at 23:54
  • 3
    Possible duplicates [here](http://stackoverflow.com/questions/1031199/adding-dictionaries-in-python) and [here](http://stackoverflow.com/questions/877295/python-dict-add-by-valuedict-2). (Note that while the first of the two links was closed as a duplicate itself, it contains my favorite answer). – David Robinson Aug 06 '12 at 23:54

1 Answers1

2

You say you want to add the values, but not what type they are. If they are numeric, you may be able to use collections.Counter instead of dict

>>> from collections import Counter
>>> a = Counter({'a':1, 'b':2})
>>> b = Counter({'a':5.4, 'c':6})
>>> a + b
Counter({'a': 6.4, 'c': 6, 'b': 2})
John La Rooy
  • 295,403
  • 53
  • 369
  • 502