Python: How can I iterate through and combine multiple dictionaries based off a common key:values?

Question:

I am attempting to take a list, full of multiple dictionaries, and combine those multiple dictionaries in new dictionaries. A couple small requirements are throwing me off however.

  1. I have values for a specific key which will show up twice throughout the list, so I want to combine these two dictionaries down to one.
  2. While combining, I am hoping to use the values of other keys to become a new, unique key

Here is my current list:

supplemental_list = [
  {'i': 44, 'id': 'Qty', 'value': '-1.00'},
  {'i': 44, 'id': 'Rate', 'value': '5000.00'},
  {'i': 52, 'id': 'Qty', 'value': '-1.50'},
  {'i': 52, 'id': 'Rate', 'value': '100.00'}
]

And here is what I need the new list to look like. Notice the values of the ‘id’ key and becoming the new key, and the respective values from the ‘value’ key are the values for the new key.

supplemental_list_new = [
  {'i': 44, 'Qty': '-1.00', 'Rate': '5000.00'},
  {'i': 52, 'Qty': '-1.50', 'Rate': '100.00'}
]

I had taken a few attempts and this was getting close, I have included a snippet below. It appears to properly compile a single dictionary for ‘i’ 44, but I know this isn’t quite correct. How can I tackle this or what other approach would work?

supplemental_list_new = {}
for i in supplemental_list:
    for key in i.keys():
        supplemental_list_new['i'] = supplemental_list[0]['i']
        supplemental_list_new['Qty'] = supplemental_list[0]['value']
        supplemental_list_new['Rate'] = supplemental_list[1]['value']
Asked By: Srichard90

||

Answers:

You can use a defaultdict to store the values for each i.

from collections import defaultdict
res = defaultdict(dict)
for d in supplemental_list:
    res[d['i']] |= {'i' : d['i'], d['id'] : d['value']}
print([*res.values()])
# [{'i': 44, 'Qty': '-1.00', 'Rate': '5000.00'}, {'i': 52, 'Qty': '-1.50', 'Rate': '100.00'}]
Answered By: Unmitigated
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.