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'}
Python 2 uses an undocumented order implemented as a .__cmp__()special method.
.__cmp__()
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) ..
key=sorted
sort key (). , , :
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.
Source: https://habr.com/ru/post/1531225/More articles:Incorrect IntelliSense XML Generated for F # Record Values (VS2013) - xmlUnlock and unlock the screen of an Android phone when compiling and starting a project? - androidWhy can't I throw an exception after I throw it? - scopearray field type in essence for symfony type select field - formsGoogle Maps V3 does not remove event listener - javascriptNo libffmpeg.so for command line arguments after creating FFMPEG for android - androidserialize two different instances in a list on a single json line - jsoneBay API not working for UPC / EAN - javascriptHow to calculate percent completion in parallel? - c #Animated jerks on an Android device in titanium - androidAll Articles