infrared
infrared

Reputation: 3626

How does python sort a list of dictionaries?

Using the sorted built-in function without providing any optional arguments, how does python sort a list of dictionaries?

Upvotes: 0

Views: 1574

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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.

Upvotes: 8

mata
mata

Reputation: 69032

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?

Upvotes: 1

Related Questions