I googled around for merging dictionaries but the results I looked at were all assuming replacement of the value. That is, if you a dict like {'config_prop': 2}
, and another dict like {'config_prop': 7}
, the end result of the merge is {'config_prop': 7}
. What I want is {'config_prop': 9}
.
My naive approach is the following, which works but is quite slow.
split_output = [{'some_prop': 1}, {'some_prop': 2, 'other_prop': 19}]
combined_output = {}
for d in split_output:
if combined_output == {}:
combined_output = d.copy()
else:
for key, value in d.items():
if key in combined_output:
combined_output[key] = combined_output[key] + value # add to existing val
else:
combined_output[key] = value
I'd love to hear suggestions on a better way to do this. Thanks!
Update: I tried this but it is considerably slower than my original code:
final_count = Counter()
for d in split_output:
final_count += Counter(d)
final_output = dict(final_count)