Python3 get key from dict.items() maximum value

Question:

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.

Asked By: RodolfoAP

||

Answers:

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

max(d, key=d.get)
Answered By: stukituk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.