Home > Blockchain >  Python3 get key from dict.items() maximum value
Python3 get key from dict.items() maximum value

Time:01-20

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.

Thanks in advanced.

CodePudding user response:

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

max(d, key=d.get)
  • Related