Dicts not ordered in python 3?

Why are dicts ordered in python2 but not in python3? I can not 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()

against.

Python 2.7.6 (default, Feb 26 2014, 12:01:28)
>>> sorted([{'a':'a'},{'b':'b'}])
[{'a': 'a'}, {'b': 'b'}
+4
source share
2 answers

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

Ordering only makes sense in a limited set of use cases and exists only because Python 2 tries to make everything orderly.

Python 3 Python; .__cmp__() , , (, ), . .

. , , . , (, key=sorted) ..

+8

sort key (). , , :

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

, " "


:, Martijn Pieters, , Python 2. , , , Python 2.

+7

Source: https://habr.com/ru/post/1531225/


All Articles