Python 从字典列表创建嵌套字典
我有以下词典列表:Python 从字典列表创建嵌套字典,python,python-2.7,dictionary,dictionary-comprehension,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': 'build
[{'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'}}
我可以迭代列表,比较“键”值的子字符串等来构建它,但我认为有一种更优雅的方法,可能是使用字典理解?这不能用字典理解来完成,因为列表元素和结果元素之间没有一对一的对应关系。您需要将多个输入合并到同一结果元素中的嵌套属性中
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']
输出不是一个字典你真的想在所需结果的每一行开始一个新的字典吗?我不认为这可以通过字典理解来完成,因为输入中的多个元素需要合并到结果中。@Barmar我的错误,更正了第二行和第三行不应该以开头的错误{酷,比我走对了方向。你的解决方案很有效,tnx