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'}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With