单条字典的排序列表?

2024-06-16 13:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,其中的各个条目作为字典,可能有不同的键。我想根据值对它们进行排序。例如

比如说

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]

排序后,(降序)

sorted_list = [{'b': 34}, {'a': 23}, {'c': 2}]

请告诉我怎么用python做


Tags: 列表字典排序条目listsortedunsorted降序
3条回答

这可以满足您的需要:

sorted_list = sorted(unsorted_list, key=lambda x: list(x.values())[0]*-1)

或者

sorted_list = sorted(unsorted_list, key=lambda x: list(x.values())[0], reverse=True)

你可以试试这个:

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]
final_data = sorted(unsorted_list, key=lambda x:x.values()[0])[::-1]

输出:

[{'b': 34}, {'a': 23}, {'c': 2}]

您需要根据dict值对元素进行排序(无论如何只有一个值),相反:

unsorted_list = [{'a': 23}, {'b': 34}, {'c': 2}]

sorted_list = sorted(unsorted_list, key = lambda d : list(d.values()), reverse=True)

结果:

[{'b': 34}, {'a': 23}, {'c': 2}]

相关问题 更多 >