QBoard » Artificial Intelligence & ML » AI and ML - Python » Getting key with maximum value in dictionary?

Getting key with maximum value in dictionary?

  • I have a dictionary: keys are strings, values are integers.

    Example:

    stats = {'a':1000, 'b':3000, 'c': 100}
    ​


    I'd like to get 'b' as an answer, since it's the key with a higher value.

    I did the following, using an intermediate list with reversed key-value tuples:

    inverse = [(value, key) for key, value in stats.items()]
    print max(inverse)[1]​

    Is that one the better (or even more elegant) approach?

     
      November 18, 2021 12:25 PM IST
    0
  • Example:

    stats = {'a':1000, 'b':3000, 'c': 100}
    

     

    if you wanna find the max value with its key, maybe follwing could be simple, without any relevant functions.

    max(stats, key=stats.get)
    

     

    the output is the key which has the max value.

     
      November 29, 2021 11:55 AM IST
    0
  • key, value = max(stats.iteritems(), key=lambda x:x[1])
    If you don't care about value (I'd be surprised, but) you can do:
    key, _ = max(stats.iteritems(), key=lambda x:x[1])
    I like the tuple unpacking better than a [0] subscript at the end of the expression. I never like the readability of lambda expressions very much, but find this one better than the operator.itemgetter(1) IMHO.
      November 19, 2021 2:59 PM IST
    0
  • You can use:

    max(d, key = d.get) 
    # which is equivalent to 
    max(d, key = lambda k : d.get(k))

    To return the key, value pair use:

    max(d.items(), key = lambda k : k[1])
    
      November 22, 2021 12:08 PM IST
    0