Reputation: 521
I have a list of dictionaries, where some keys across the dictionaries overlap, and some values overlap within and across the dictionaries:
[{'a': 0.91, 'b': 0.91, 'c': 0.9},
{'a': 0.94, 'c': 0.93, 'd': 0.91},
{'c': 0.93, 'b': 0.93, 'f': 0.92}]
I would like to merge the list of dictionaries into a single dictionary where all of the keys across the different dictionaries show up once, and the value associated with the respective key is the maximum value of the key across the different dictionaries in the original list. In this case, it would look like this:
{'a': 0.94, 'b': 0.93, 'c': 0.93, 'd': 0.91, 'f': 0.92}
Upvotes: 1
Views: 328
Reputation: 311073
I'd run over the list, and then over each dictionary and accumulate them into a result dictionary:
result = {}
for d in lst:
for k,v in d.items():
if k in result:
result[k] = max(result[k], v)
else:
result[k] = v
Upvotes: 2