首页 > 解决方案 > 将字典对象转换为字典对象列表

问题描述

我有以下 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%)'}
 ]

标签: pythonpython-3.xlistdictionary

解决方案


首先,您想要作为输出的结构不是 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%)'}}]

推荐阅读