Dict对象到Dict对象列表的转换

2024-06-02 06:40:56 发布

您现在位置: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%)'}
 ]

Tags: 列表字典结构natdictattributesserfirst
2条回答

首先,您想要作为输出的结构不是python list格式。 实际上,它也不是字典格式。你知道吗

从你的问题中,我知道你想列一份字典清单。你知道吗

首先,创建一个dictionary元素:

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

您的问题不清楚,所需的输出无效。我假设你想要一个字典列表作为你想要的输出。有几个步骤。你知道吗

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

下面是一个完整的例子。你知道吗

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

相关问题 更多 >