Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of dictionaries to nested dictionary

Tags:

python

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'}
}
like image 682
Roger Sanchez Avatar asked Sep 25 '12 15:09

Roger Sanchez


1 Answers

Use a defaultdict for ease of processing these entries:

output = defaultdict(dict)

for person in people:
    output[person['Name']][person['Attribute']] = person['Value']
like image 148
Martijn Pieters Avatar answered Sep 19 '22 06:09

Martijn Pieters