[SOLVED] Getting the key for second maximum value from a dictionary, Python

Issue

I am doing it this way but if there is any easy/efficient way of doing it

def get_second_max(dic):
    count = 0
    ind =0
    vals = list(dic.values())
    for val in vals:
        count = 0
        for value in vals:
            if value > val:
                count += 1
            if count > 2:
                break
        if count == 1:
            ind = vals.index(val)
    return list(dic.keys())[ind]

Solution

Sort the dict keys by their value and get the second to last item:

sorted(dic, key=dic.get)[-2] 

Answered By – vaizki

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published.