从字典列表创建嵌套字典
Created a nested dictionary from a 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'}]
我想从中创建一个嵌套字典:
{'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'}}
我可以遍历列表,比较 'Keys' 值的子字符串等来构建它,但我认为有更优雅的方法,也许使用字典理解?
这不能用字典理解来完成,因为列表元素和结果元素之间没有一对一的对应关系。您需要将多个输入合并到同一结果元素中的嵌套属性中。
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']
我有以下词典列表:
[{'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'}}
我可以遍历列表,比较 'Keys' 值的子字符串等来构建它,但我认为有更优雅的方法,也许使用字典理解?
这不能用字典理解来完成,因为列表元素和结果元素之间没有一对一的对应关系。您需要将多个输入合并到同一结果元素中的嵌套属性中。
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']