Feed on
Posts
Comments

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


Bookmark and Share

if that was helpful ...

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

26 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])[1]

  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

    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

  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])[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
    ”’

  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[1])

  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

    Mario wins this thread.

  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 29 Jun 2021 at 12:24 pm read article

    read article

    find the key for the minimum (or maximum) value in a python dictionary » from the desk of stinkpot

  18. 
    این پیام مشاوره و پیشنهاد مناسب از باب کسانی است که می خواهند دوروبر محتویات هماننده به این مطلب مطالعه بیشتری داشته باشند

  19. 
    من آسوده خاطر هستم که درون طولانی
    اینترنت پیام قرین بوسیله این نبا بود ندارد برای این که مطلب طولانی و مستوفا ی
    پیرامون این مبحث است

  20. 
    عبد تا به حال پیام به این اتساق در اینترنت نخوانده بودم بسیار جذاب و آزگار بود و مقاله جالب شما به خاطر فراوان
    از ملاقات کنندگان اینترنت نازل است

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

  22. 
    محتوا ی این یادداشت از نظر وافر
    از افراد ارزان و کامل نیست ولی جانباز از محتویات محل استقرار رادار ها
    و بلاگ ها پیرامون این مطلب در وب وجود
    دارند که می توان از آنها استفاده بهتری داشت

  23. on 01 Dec 2024 at 5:01 pm about

    For example, the Mega Millions reached $1,537 billion earlier than it was gained on October twenty third, 2018.
    By the best way, this was the largest lottery prize in the world that was gained
    with a single ticket. Multiple lottery winners do exist, though that
    is rare. Since its founding in 1967, the new York Lottery has collected $48.Forty three billion for schooling.
    With presidential candidate Tom Steyer speaking about his signing
    of The Giving Pledge, it may be worth mentioning that Bill
    Gates was a founding member of the campaign back in 2010.

    The Giving Pledge is a campaign that encourages the wealthiest folks
    to donate nearly all of their wealth instead of hoarding it
    for themselves and their descendants.

  24. on 08 Dec 2024 at 10:32 pm casino

    As already talked about, all promotions are geared toward energetic gamers who place bets and win actual cash. There are libraries hooked up to schools, churches and clubs, and most of the bigger towns possess public libraries. You even have the option to choose “Quick Pick,” or “QP” on your ticket to have the computer randomly assign you numbers as an alternative of choosing your own numbers if you’d like. On May 11, 2022, Crow incorrectly called the mega ball quantity as a “6″ as an alternative of the actual “9,” the numbers printed on the ball have an underline to indicate their appropriate orientation.

  25. on 19 Dec 2024 at 8:19 am peepshow

    Awesome information, With thanks!

  26. on 22 Dec 2024 at 1:23 am dick

    You expressed it fantastically!

Did I get this wrong? Let me know!

Trackback URI | Comments RSS