0

I'm not a Python programmer. Having a Python3 dictionary like this,

d={"a":"1", "b":"2"}

How can I get the key for the largest value (that is, 'b') in a simple form?

Of course, I can write some spaghetti,

def get_max_key(data):
    MAX=''
    MAXKEY=''
    for x in data.items():
        if x[1]>MAX:    
            MAX=x[1]
            MAXKEY=x[0]
    return MAXKEY

But that's silly. I know there should be a pythonic way to do it, possibly a one-liner.

Hille
  • 2,123
  • 22
  • 39
RodolfoAP
  • 743
  • 1
  • 7
  • 18

1 Answers1

1

To get the key of the maximum value in a dictionary, just use this:

max(d, key=d.get)
stukituk
  • 168
  • 1
  • 8