0

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}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
acciolurker
  • 429
  • 4
  • 15
  • Does this answer your question? [merging two python dicts and keeping the max key, val in the new updated dict](https://stackoverflow.com/questions/54420664/merging-two-python-dicts-and-keeping-the-max-key-val-in-the-new-updated-dict) – Anatole Sot Nov 25 '20 at 21:53

1 Answers1

1

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
Mureinik
  • 297,002
  • 52
  • 306
  • 350