从词典列表创建嵌套的词典

时间:2019-11-21 20:31:19

标签: python python-2.7 dictionary dictionary-comprehension

我有下面的词典列表:

[{'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'}]

我要从中创建这样的嵌套字典:

{'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'}}

我可以遍历列表,比较“键”等值的子字符串以构建此字符串,但我认为还有一种更优雅的方法,也许使用字典理解功能?

1 个答案:

答案 0 :(得分:1)

这不能用字典理解来完成,因为列表元素和结果元素之间没有一一对应的关系。您需要将多个输入合并到同一结果元素中的嵌套属性中。

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']