I have below dictionary:
d = {1: 'zz', 2: 'we', 'as': 'dfda', 'x': 'zyz'}
And max
and min
return following:
max(d)
'x'
min(d)
1
How do max
and min
really work in this case?
I have below dictionary:
d = {1: 'zz', 2: 'we', 'as': 'dfda', 'x': 'zyz'}
And max
and min
return following:
max(d)
'x'
min(d)
1
How do max
and min
really work in this case?
max
and min
work on iterables. If you try to convert a dictionary into an iterable, you get back its keys. So, max(d)
is sort of the same as max(1,2,'as','x')
. There are some details on the ordering of the various builtin types here. As an example, 1< "a"
is True
. This is used to find the maximum of the list. Similarly for min
. As a note, I wouldn't recommend doing something like this in production code.
min
and max
functions, when applied on dictionaries, they work on the keys of the dictionary.
In your case, they have to work on
[1, 2, 'as', 'x']
As you can see, there are multiple types of data present in it. In Python 2.7, if the types are different, then the string value of the types are used for comparison.. Quoting from that section,
Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. (The rules for comparing objects of different types should not be relied upon; they may change in a future version of the language.)
So if you actually sort the dictionary keys,
>>> sorted(d)
[1, 2, 'as', 'x']
As you can see now, the smallest is 1
and the biggest is x
.