Find max or min in Python dictionary

Wednesday, August 27th, 2008
Advertisement

Subscribe.
Enter your email:

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?

Applying

max(mydict)

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) )
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>