繁体   English   中英

将Dict对象转换为dict对象列表

[英]Conversion of Dict object into a list of dict object

我有以下字典结构

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%)'}
 ]

首先,您要输出的结构不是python list格式。 实际上,它也不是字典格式。

从您的问题中,我了解到您想列出字典。

首先,制作一个字典元素:

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%)'}}]

您的问题不清楚,并且所需的输出无效的Python。 我假设您要使用词典列表作为所需的输出。 有几个步骤。

  1. 定义您的订单 Python不知道字符串“ Fourth”应在“ Third”之后。
  2. 对字典项应用排序 字典在Python中是无序的(除非您使用的是3.7+)。
  3. 对enumerate使用理解可构造列表结果。

这是一个完整的例子。

d = {'Attributes': {'Fifth': 'blind (19.33%)',
                    'First': 'Art (40.0%)',
                    'Fourth': 'Ser (20.0%)',
                    'Second': 'Nat (21.33%)',
                    'Third': 'per (20.67%)'}}

order = {v: k for k, v in enumerate(('First', 'Second', 'Third', 'Fourth', 'Fifth'))}

sorter = sorted(d['Attributes'].items(), key=lambda x: order[x[0]])

L = [dict(enumerate({k: v} for k, v in sorter))]

print(L)

[{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%)'}}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM