Question

Why are dicts orderable in python2, but not in python3? I can't find it anywhere in the documentation.

Python 3.3.4 (default, Feb 11 2014, 16:14:21)
>>> sorted([{'a':'a'},{'b':'b'}])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() < dict()

vs.

Python 2.7.6 (default, Feb 26 2014, 12:01:28)
>>> sorted([{'a':'a'},{'b':'b'}])
[{'a': 'a'}, {'b': 'b'}
Was it helpful?

Solution

Python 2 uses an undocumented ordering, implemented as a .__cmp__() special method.

The ordering only makes sense in a limited set of use-cases, and only exists because Python 2 tries to make everything orderable.

Python 3 drastically cleaned up Python's ordering story; .__cmp__() is gone, and only types that actually have a natural ordering (such as numbers and strings) now support ordering. For everything else, you'll need to explicitly define an ordering.

Dictionaries do not have a natural ordering. If you do need to order dictionaries, you need to define an explicit order that makes sense for your use case. If that means comparing just the keys, do so (e.g. use key=sorted), etc.

OTHER TIPS

You'll need to sort with a key (documentation). Only you know what key you want, but here's one example:

>>> dicts = [{'a':'a'},{'b':'b'}]
>>> sorted(dicts, key=lambda x:sorted(x.keys()))
[{'a': 'a'}, {'b': 'b'}]

This is sorting by keys, where the dict with the "lowest" key comes first


Edit: as pointed out by Martijn Pieters, this answer describes exactly how Python 2 does it. But you should sort in the way that makes sense to your situation, which may be fundamentally different from how Python 2 does it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top