Feed on
Posts ## find the key for the minimum (or maximum) value in a python dictionary

assume you’ve got a python dictionary a and you’d like to find the key associated with the minimum (or maximum) value in the dictionary:

>>> a = dict()
>>> a['me'] = 5
>>> a['you'] = 5
>>> a['her'] = 6
>>> a['him'] = 245
>>> print a
{‘me’: 5, ‘you’: 5, ‘him’: 245, ‘her’: 6}

to find the key associated w/ the smallest value, simply invert the python dictionary; now, all the old values will be the keys.  then, simply find the smallest key.  note, however, that if two original values have the same key, only one of the original keys will be printed:

>>> b = dict(map(lambda item: (item,item),a.items()))
>>> min_key = b[min(b.keys())]
>>> print min_key
you ### if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

### 20 Responses to “find the key for the minimum (or maximum) value in a python dictionary”

1. on 24 Oct 2006 at 7:35 pm lawrence

i like this better:

>>> d = {‘bob’:4, ‘krishna’:9, ‘hikari’:5}
>>> e = d.keys()
>>> e.sort(cmp=lambda a,b: cmp(d[a],d[b]))
>>> e
['bob', 'hikari', 'krishna']

2. on 24 Oct 2006 at 7:44 pm Lawrence David

that was sick lawrence. (i wish i was a python gangsta like you.)

3. on 14 Dec 2007 at 10:29 am Ryan

Yet another way, which I prefer, requires python 2.4+.

>>> a = {‘b’ : 1, ‘a’ : 2, ‘c’ : 5, ‘d’:4}
>>> b = a.keys()
>>> b.sort( key = a.__getitem__ )
>>> b
['b', 'a', 'd', 'c']

4. on 26 Feb 2008 at 10:53 am Jochen

with python 2.5+ you can just do directly
max(d,key = lambda a: d.get(a))
which avoids the sorting

5. on 26 Feb 2008 at 11:06 am Jochen

hmm, this also works for earlier pythons
max([ (d[x],x) for x in d])

6. on 26 Feb 2008 at 11:23 am Lawrence David

oh, of course, you’re totally right jochen! thanks for making me a little more knowledgeable about python today!

7. on 29 Jun 2008 at 12:30 pm Joe

Jochen: What are d and a in your example?

8. on 28 May 2009 at 1:05 am Kirk James Gaughan

Anyways, here’s the answer to Joe’s question:

‘d’ is the name of your dictionary variable, ‘a’ is just a temporary variable used in the lambda expression

9. on 17 Aug 2009 at 6:44 am Libell

alchemy vs metallurgy

please find a little profiling on this methods
and the good old classic manual one

import datetime

a = {‘b’ : 1, ‘a’ : 2, ‘c’ : 5, ‘d’:4 }

t = datetime.datetime.now()
for i in range (1,1000000) :
ll = max([ (a[x],x) for x in a])
b = datetime.datetime.now()
print b – t , ll

t = datetime.datetime.now()
for i in range (1,1000000) :
nn = max(a ,key = lambda x: a.get(x))
b = datetime.datetime.now()
print b – t ,nn

t = datetime.datetime.now()
for i in range (1,1000000) :
b = a.keys()
b.sort( key = a.__getitem__ )
mm = b[-1]
print datetime.datetime.now() – t ,mm

t = datetime.datetime.now()
for i in range (1,1000000) :
mmm = -99999999
qui = None
for k, x in a.iteritems():
if x > mmm :
mmm = x
qui = k

print datetime.datetime.now() – t , qui

”’
0:00:03.750000 c
0:00:03.719000 c
0:00:03.422000 c
0:00:02.859000 c
”’

10. on 08 Mar 2010 at 10:43 pm ignacio

The 4th is probably just faster because you don’t have to lookup the element each time (hash). You can combine that with the above:

max(a.iteritems(),key=lambda x:x)

11. on 23 Mar 2010 at 7:50 am Mario Orne Diaz Anadon

I think I am going to win the competition!

The shortest solution is to write:

a = dict(((1,3),(0,-1),(3,3)))
m = max(a, key=a.get)

12. on 19 Feb 2011 at 8:48 pm Jawaiah Hunter

Wow Mario that is truly elegant and Pythonic. Rock on bro.

13. on 07 Mar 2011 at 7:30 am Mikko

Thanks guys this was very helpful!

14. on 12 Apr 2011 at 11:56 am Forcasa

15. on 02 Feb 2012 at 1:28 pm THe üBER p12

Acually the shortest way to write is:

a=dict(((1,3),(0,-1),(3,3))); m=max(a,key=a.get)

This is much shorter… 8-|

But it’s ok. I have tolerance for newbies.

16. on 18 Jan 2013 at 5:56 pm Layne

Gents:

What if you wanted to find out it the two highest Keys had the same value? – Basically I’m looking for the highest value and reporting the Key – but I also need to identify if the 2 top Keys have the same value – i.e. co-dominant.

17. on 14 Jun 2017 at 11:58 pm موقع جزر المالديف

Egypt Excursions offer a wide range of tours,
excursions and trips in Hurghada, some of which are water
based akin to snorkeling and diving and some based mostly in the deserts that encompass Hurghada and further on to Egypt’s other great cities resembling Cairo and Luxor.

18. on 17 Jul 2017 at 4:19 pm عروض الفنادق في دبي

In the event you cancel a reserving to make changes, all of the Vitality Lodge Assortment
guidelines will apply to the new booking.

19. on 10 Jun 2018 at 10:45 am Rod

Both men and women aге readiⅼy available to
chast with.

20. on 13 Jun 2018 at 6:05 am Erwin Rivet 