How To Combine Multiple Dicts, Summing The Values Of Common Keys (and Retaining Those With Value 0) In Python?
Given three dicts d1, d2 and d3: d1 {'a':1,'b':2,'c':3, 'd':0) d2 {'b':76} d3 {'a': 45, 'c':0} There are some key names that are common to more than one dict (and in reality, th
Solution 1:
You could use update
instead of +
with Counter
if you want the 0 keys to persist:
>>>c = Counter()>>>for d in d1, d2, d3:... c.update(d)...>>>c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})
(This is probably a dup, but I can't find it right now.)
Solution 2:
collections.defaultdict
to the rescue
importcollectionsd= collections.defaultdict(int)
for thing in [d1, d2, d3]:
for k, v in thing.items():
d[k] += v
Solution 3:
UNTESTED:
defmerge_dicts(*dicts):
res = {}
for key inset(sum(map(list, dicts), [])):
res[key] = 0for dct in dicts:
res[key] += dct.get(key, 0)
return res
Example usage:
merge_dicts(d1, d2, d3)
Post a Comment for "How To Combine Multiple Dicts, Summing The Values Of Common Keys (and Retaining Those With Value 0) In Python?"