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'}
}
This will produce the data structure the questioner wants and also makes it easy for him to maintain it:
An example of paths(): https://stackoverflow.com/a/16298347/2334951
I intend to add more functionality to it in the future. You can find most recent version here: https://github.com/gneposis/gntools/blob/master/src/gntools/core/collections/nestdict.py
Also covers these questions:
EDIT: Updated to new and tested version.
Usage:
Use a
defaultdict
for ease of processing these entries: