Wednesday, August 27, 2008

Find max or min in Python dictionary

Suppose that mydict is a dictionary defined by
mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4}
How to find the key for the max or min value in the items?

would produce 'd'. This is wrong. The answer should be 'c'.

Doing it this way, the Python try to find the max in the key part. In this case, 'd' is the max, in alphabetical order.

The correct way is,
max(mydict, key = lambda x: mydict.get(x) )
Similarly, to find the min,
min(mydict, key = lambda x: mydict.get(x) )