简体   繁体   中英

How does python sort a list of dictionaries?

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

Python 2 does attempt to provide an ordering (it does so for all types), first based on length (shorted dicts first), if the lengths are equal then by keys (a smaller key goes first), then if all keys are equal then on values (smaller values go first); see the characterize and dict_compare functions in the dictobject.c source code.

Short demo:

>>> sorted([{1:2}, {}])
[{}, {1: 2}]
>>> sorted([{1:2}, {0:1}])
[{0: 1}, {1: 2}]
>>> sorted([{1:2}, {1:1}])
[{1: 1}, {1: 2}]

In Python 3, it doesn't sort them at all; sorting dicts really makes no sense:

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

See the Ordering Comparisons section of the What's New in Python 3 document.

It doesn't (at least for python3):

>>> x = [{4:1}, {3:2}, {1:2}, {5:6}]
>>> x
[{4: 1}, {3: 2}, {1: 2}, {5: 6}]
>>> sorted(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()

There isn't a reasonable default for specifying an ordering of dicts, so dicts are unorderable.

This behaviour has changed from python2, because comparisions have been reworked in python3. Before it was possible to compare almost anything using cmp() , which reflects in the ordering of lists. python3 fixes this, cmp() doesn't exist and comparisions are done using rich comparision methods, wich make only things comparable that really are, or how much sense does something like cmp(Exception(), 42) make?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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