Dictionary __gt__ and __lt__ implementation

I experimented with Python dictionaries and found that __gt__ and __lt__ implemented for dictionaries.

I tested them, and it seems that they are somehow comparing the keys, but it is not entirely clear to me how this is done; for example, I'm not quite sure how {1: 1} > {'0': 0} returns False (in fact, '0' > 100000 also returns True ).

Is there any document specific to the implementation of these two functions?

+5
source share
1 answer

The documentation has a comparison section . In particular:

Objects of different types, except for different numeric types and different types of strings, never compare the same; such objects are ordered sequentially, but arbitrarily (so that sorting a heterogeneous array gives a consistent result).

The reason for this behavior is:

 >>> '0' < 0 False >>> 0 < '0' True 

in CPython is that the selected comparison method was "sequentially, but randomly" alphabetically sorted by type name and 'str' > 'int' :

CPython implementation details . Objects of different types, except for numbers, are ordered by their type names; objects of the same type that do not support proper comparison are ordered by their address.

This behavior has been changed for Python 3.x , and you can no longer compare heterogeneous types (or dictionaries, for that matter):

 >>> '0' > 0 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> '0' > 0 TypeError: unorderable types: str() > int() >>> {'a': None} > {'b': None} Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> {'a': None} > {'b': None} TypeError: unorderable types: dict() > dict() 

In terms of dictionaries, in particular, they are sorted so that:

 d1 > d2 

becomes:

 (len(d1) > len(d2) or (len(d1) == len(d2) and sorted(d1.items()) > sorted(d2.items())) 

(this can be seen in the source code of CPython ). Therefore, if they do not have the same length, the β€œlonger” is β€œlonger”:

 >>> {1: 2, 3: 4} > {1: 2} True 

if they have the corresponding keys, then with larger values ​​"greater":

 >>> {1: 2} > {1: 1} True 

and if they have inappropriate keys, then one with the "big" keys is "bigger":

 >>> {1: 2} > {2: 1} False 
+5
source

All Articles