蟒蛇。我如何按列表值对字典元组进行排序

时间:2019-09-21 15:48:37

标签: python

我在元组中有一些格言:

a = ({'row_n': 1, 'row_section': None, 'TM': 'FORD', 'article': 'F5OZ5311CA', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '2', '1374,13']}},
{'row_n': 2, 'row_section': None, 'TM': 'FORD', 'article': 'FOVY7E395B', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '3', '824,48']}}
{'row_n': 3, 'row_section': None, 'TM': 'FORD', 'article': 'RH170', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '5', '412,24']}})

我需要按['size_measures_multi'] [size]排序该字典,并给出类似的结果:

a = ({'row_n': 1, 'row_section': None, 'TM': 'FORD', 'article': 'F5OZ5311CA', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '2', '1374,13']}},
{'row_n': 2, 'row_section': None, 'TM': 'FORD', 'article': 'FOVY7E395B', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '3', '824,48']}}
{'row_n': 3, 'row_section': None, 'TM': 'FORD', 'article': 'RH170', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '5', '412,24']}})

我尝试

for i in a:
    {x: sorted(i['size_measures_multi']['size']) for x in i.keys()}

但这给我不好的结果。

我该怎么做。我会很感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

只需使用sorted的关键参数:

a = ({'row_n': 1, 'row_section': None, 'TM': 'FORD', 'article': 'F5OZ5311CA', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '2', '1374,13']}},
{'row_n': 2, 'row_section': None, 'TM': 'FORD', 'article': 'FOVY7E395B', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '3', '824,48']}},
{'row_n': 3, 'row_section': None, 'TM': 'FORD', 'article': 'RH170', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '5', '412,24']}})

result = sorted(a, key=lambda d: tuple(d['size_measures_multi']['size']))

for e in result:
    print(e)

输出

{'row_n': 1, 'row_section': None, 'TM': 'FORD', 'article': 'F5OZ5311CA', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '2', '1374,13']}}
{'row_n': 2, 'row_section': None, 'TM': 'FORD', 'article': 'FOVY7E395B', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '3', '824,48']}}
{'row_n': 3, 'row_section': None, 'TM': 'FORD', 'article': 'RH170', 'description': '', 'size_measures_multi': {'unit': None, 'additional_field': None, 'size': ['1', '5', '412,24']}}