Maybe I am not understanding you question right, but are you trying to add all the values from each of the dictionaries together into one final dictionary? If so:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 5, 'c': 1, 'd': 9}
dict3 = {'d': 1, 'e': 7}
def add_dict(to_dict, from_dict):
for key, value in from_dict.iteritems():
to_dict[key] = to_dict.get(key, 0) + value
result = dict(dict1)
add_dict(result, dict2)
add_dict(result, dict3)
print result
This yields: {'a': 1, 'c': 4, 'b': 7, 'e': 7, 'd': 10}
It would be really helpful to post what the expected outcome should be for your question.
EDIT:
For an arbitrary amount of dictionaries:
result = dict(dicts[0])
for dict_sum in dicts[1:]:
add_dict(result, dict_sum)
print(result)
If you really want to fix the code from your original question in the format it is in:
- You are using
dict1[k]+=1
when you should be performing dict1[k]+=dict2.get(k, 0)
.
- The introduction of
get
removes the need to check for its existence with an if statement.
- You need to iterate though
dict2
and dict3
to introduce new keys from them into dict1
- (not really a problem, but worth mentioning) In the if statement to check if the key is in the dictionary, it is recommended to simply the operation to
if k in dict2:
(see this post for more details)
With the amazing built-in library found by @DisplacedAussie, the answer can be simplified even further:
from collections import Counter
print(Counter(dict1) + Counter(dict2) + Counter(dict3))
The result yields: Counter({'d': 10, 'b': 7, 'e': 7, 'c': 4, 'a': 1})
The Counter
object is a sub-class of dict
, so it can be used in the same way as a standard dict
.