Reputation: 627
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
Upvotes: 0
Views: 1782
Reputation: 304235
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})
Upvotes: 2