python如何对字典列表进行排序?

inf*_*red 0 python sorting

使用sorted内置函数而不提供任何可选参数,python如何对字典列表进行排序?

Mar*_*ers 8

Python 2确实尝试提供排序(它对所有类型都这样做),首先基于长度(首先是shortts dicts),如果长度等于然后是键(首先是较小的键),那么如果所有键都相等则关于价值(较小的值先行); 看到characterizedict_compare功能dictobject.c源代码.

简短演示:

>>> sorted([{1:2}, {}])
[{}, {1: 2}]
>>> sorted([{1:2}, {0:1}])
[{0: 1}, {1: 2}]
>>> sorted([{1:2}, {1:1}])
[{1: 1}, {1: 2}]
Run Code Online (Sandbox Code Playgroud)

在Python 3中,它根本不对它们进行排序; 排序dicts真的没有意义:

>>> sorted([{}, {}])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()
Run Code Online (Sandbox Code Playgroud)

请参阅Python 3中的新功能文档的" 排序比较"部分.