Mike
Mike

Reputation: 3

Created a nested dictionary from a list of dictionaries

I have the following list of dictionaries:

[{'Key': 'building/code/mp-10', 'Value': 'BE03:33'}, 
{'Key': 'building/code/mp-10/location', 'Value': 'BE03'}, 
{'Key': 'building/code/mp-10/street', 'Value': 'street5'}, 
{'Key': 'building/code/mp-10/note', 'Value': None}, 
{'Key': 'building/code/mp-10/number', 'Value': '33'}, 
{'Key': 'building/code/mp-1000', 'Value': 'DU05:99'}, 
{'Key': 'building/code/mp-1000/location', 'Value': 'DU05'}, 
{'Key': 'building/code/mp-1000/street',     'Value': 'street100'}, 
{'Key': 'building/code/mp-1000/note', 'Value': None}, 
{'Key': 'building/code/mp-1000/number', 'Value': '99'}, 
{'Key': 'building/code/mp-104', 'Value': 'DF88:05'},
{'Key': 'building/code/mp-104/location', 'Value': 'DF88'}, 
{'Key': 'building/code/mp-104/street', 'Value': 'street599'}, 
{'Key': 'building/code/mp-104/note', 'Value': None}, 
{'Key': 'building/code/mp-104/number', 'Value': '05'}]

From which I want to created a nested dictionary as such:

{'mp-10':{'location':'BE03','street':'street5','note':None,'number':'33'},
'mp-1000':{'location':'DU05','street':'street100','note':None,'number':'99'},
'mp-104':{'location':'DF88','street':'street599','note':None,'number':'05'}}

I could iterate over the list, compare the substring of the values of the 'Keys' etc to build this but I assume there is a more elegant way, perhaps using dictionary comprehension?

Upvotes: 0

Views: 53

Answers (1)

Barmar
Barmar

Reputation: 780879

This can't be done with a dictionary comprehension, because there isn't a one-to-one correspondence between the list elements and the result elements. You need to merge multiple inputs into nested properties in the same result element.

result = {}
for d in input_list:
    keys = d['Key'].split('/')
    if len(keys) == 3:  # /building/code/XXX
        result[keys[2]] = {}
    else:               # /building/code/XXX/YYY
        result[keys[2]][keys[3]] = d['Value']

Upvotes: 1

Related Questions