Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dicts are not orderable in python 3?

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'}
like image 802
Matt Woelk Avatar asked Mar 11 '14 18:03

Matt Woelk


Video Answer


1 Answers

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.

like image 63
Martijn Pieters Avatar answered Sep 21 '22 09:09

Martijn Pieters