find the key for the minimum (or maximum) value in a python dictionary
October 11th, 2006 by Lawrence David
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[1],item[0]),a.items()))
>>> min_key = b[min(b.keys())]
>>> print min_key
you
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']
that was sick lawrence. (i wish i was a python gangsta like you.)
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']
with python 2.5+ you can just do directly
max(d,key = lambda a: d.get(a))
which avoids the sorting
hmm, this also works for earlier pythons
max([ (d[x],x) for x in d])[1]
oh, of course, you’re totally right jochen! thanks for making me a little more knowledgeable about python today!
Jochen: What are d and a in your example?
Found this page via Google, so I’m sure others are probably still reading it too… although it’s very old by now…
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
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])[1]
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
”’
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[1])
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)
Wow Mario that is truly elegant and Pythonic. Rock on bro.
Thanks guys this was very helpful!
Mario wins this thread.
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.
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.
read article
find the key for the minimum (or maximum) value in a python dictionary » from the desk of stinkpot

این پیام مشاوره Ùˆ پیشنهاد مناسب از باب کسانی است Ú©Ù‡ Ù…ÛŒ خواهند دوروبر Ù…Øتویات هماننده به این مطلب مطالعه بیشتری داشته باشند

من آسوده خاطر هستم که درون طولانی
اینترنت پیام قرین بوسیله این نبا بود ندارد برای این Ú©Ù‡ مطلب طولانی Ùˆ مستوÙا ÛŒ
پیرامون این مبØØ« است

عبد تا به Øال پیام به این اتساق در اینترنت نخوانده بودم بسیار جذاب Ùˆ آزگار بود Ùˆ مقاله جالب شما به خاطر Ùراوان
از ملاقات کنندگان اینترنت نازل است

سلام . غلام قسم می خورم که این
مطلب رسا است و شاید هیچگاه کس نتواند نبا مشابه بوسیله این مطلب
را اندر وبلاگ نمودار کند چون کثیر کامل است

Ù…Øتوا ÛŒ این یادداشت از نظر واÙر
از اÙراد ارزان Ùˆ کامل نیست ولی جانباز از Ù…Øتویات Ù…ØÙ„ استقرار رادار ها
و بلاگ ها پیرامون این مطلب در وب وجود
دارند Ú©Ù‡ Ù…ÛŒ توان از آنها استÙاده بهتری داشت