There are a number of questions on this topic but I have not yet been able to adapt solutions to fit my case. Supposed I have a list of dictionaries that I got from a flat file:
[{'Name': 'Jim', 'Attribute': 'Height', 'Value': '6.3'},
{'Name': 'Jim', 'Attribute': 'Weight', 'Value': '170'},
{'Name': 'Mary', 'Attribute': 'Height', 'Value': '5.5'},
{'Name': 'Mary', 'Attribute': 'Weight', 'Value': '140'}]
and I want to convert it to a nested dictionary such that the attribute/value pairs are associated to each name:
{
'Jim': {'Height': '6.3', 'Weight': '170'},
'Mary': {'Height': '5.5', 'Weight': '140'}
}
Use a defaultdict
for ease of processing these entries:
output = defaultdict(dict)
for person in people:
output[person['Name']][person['Attribute']] = person['Value']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With