selinap.com

To leave furtively and stealthily.

Home » Python

Find max or min in Python dictionary

August 27th, 2008

Suppose that mydict is a dictionary defined by

1
mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4}

How to find the key for the max or min value in the items?

Applying

1
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,

1
max(mydict, key = lambda x: mydict.get(x) )

Similarly, to find the min,

1
min(mydict, key = lambda x: mydict.get(x) )

Related Articles:

Popular Articles:

Spread/Promote this article.

Digg | Del.icio.us | Stumble | Y! MyWeb | Y! Buzz | Fave It! | Reddit

Subscribe for free.

 Subscribe to Selinap.com feed right now!

 Get Updates by Email

Tags: , , ,

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> <pre lang="" line="">


© Copyright 2008 - 2009 selinap.com
Entries (RSS) and Comments (RSS).