首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字典列表创建嵌套字典

从字典列表创建嵌套字典
EN

Stack Overflow用户
提问于 2019-11-22 04:31:20
回答 1查看 44关注 0票数 0

我有以下字典列表:

代码语言:javascript
复制
[{'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'}]

我想从其中创建一个嵌套字典,如下所示:

代码语言:javascript
复制
{'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'}}

我可以遍历列表,比较“键”的值的子字符串等来构建它,但我假设有一种更优雅的方法,也许是使用字典理解?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-22 04:50:31

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

代码语言:javascript
复制
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']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58983271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档