0

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Dharmit
  • 5,498
  • 2
  • 27
  • 30
  • 1
    Could you clarify what you're asking? Have you looked at e.g. `sorted(d)`? – jonrsharpe Jan 11 '15 at 08:24
  • http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int – Maroun Jan 11 '15 at 08:28
  • 1
    It should be noted that this would produce a TypeError in python 3 as python 3 considers there to be no natural ordering between ints and strings. – Dunes Jan 11 '15 at 08:57

2 Answers2

2

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.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
1

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497