python - 将字典对象转换为字典对象列表
问题描述
我有以下 dict 结构
d = {'Attributes': {'Fifth': 'blind (19.33%)',
'First': 'Art (40.0%)',
'Fourth': 'Ser (20.0%)',
'Second': 'Nat (21.33%)',
'Third': 'per (20.67%)'}}
需要转换成如下结构的字典项列表
[ 0: {'First': 'Art (40.0%)'},
1: {'Second': 'Nat (21.33%)'},
2: {'Third': 'per (20.67%)'},
3: {'Fourth': 'Ser (20.0%)'},
4: {'Fifth': 'blind (19.33%)'}
]
解决方案
首先,您想要作为输出的结构不是 pythonlist
格式。实际上,它也不是字典格式。
从您的问题中,我了解到您想要列出字典。
首先,制作一个字典元素:
0: {'First': 'Art (40.0%)'}
至
{0: {'First': 'Art (40.0%)'}}
然后,您将准备好制作一个字典列表,您的数据结构将如下所示:
[ {0: {'First': 'Art (40.0%)'}},
{1: {'Second': 'Nat (21.33%)'}},
{2: {'Third': 'per (20.67%)'}},
{3: {'Fourth': 'Ser (20.0%)'}},
{4: {'Fifth': 'blind (19.33%)'}}
]
你可以检查结构:
list = [ {0: {'First': 'Art (40.0%)'}},
{1: {'Second': 'Nat (21.33%)'}},
{2: {'Third': 'per (20.67%)'}},
{3: {'Fourth': 'Ser (20.0%)'}},
{4: {'Fifth': 'blind (19.33%)'}}
]
print(type(a))
print(type(list[0]))
输出:
<class 'list'>
<class 'dict'>
和代码
dict_value = {'Attributes': {'Fifth': 'blind (19.33%)',
'First': 'Art (40.0%)',
'Fourth': 'Ser (20.0%)',
'Second': 'Nat (21.33%)',
'Third': 'per (20.67%)'}}
order = {value: key for key, value in enumerate(('First', 'Second', 'Third', 'Fourth', 'Fifth'))}
sorted_form = sorted(dict_value['Attributes'].items(), key=lambda d: order[d[0]])
final_list = [dict(enumerate({key: value} for key, value in sorted_form))]
print(final_list)
生产
[{0: {'First': 'Art (40.0%)'}, 1: {'Second': 'Nat (21.33%)'}, 2: {'Third': 'per (20.67%)'}, 3: {'Fourth': 'Ser (20.0%)'}, 4: {'Fifth': 'blind (19.33%)'}}]
推荐阅读
- mysql - 在同一行按名称分组,不包括 NULL 值
- flutter - 使用 GitHub 操作创建文件夹并注入 JSON 文件
- html - 无法为 mydatepicker 插入角色或动态更新选项卡索引
- docker - 错误:无法在节点“rabbit@localhost”上执行操作
- object - 我可以编写一个行为类似于哈希的对象吗?
- c++ - 指针事件 WxWidgets WebView
- git - 将 git 存储库拆分为私有和公共存储库
- amazon-web-services - aws s3 命令无法从 bash 文件正常工作
- javascript - 仅当字符串不为空时才运行特定的 $match 查询
- android - 防止改变窗口高度