Home > Software engineering >  Getting the key for second maximum value from a dictionary, Python
Getting the key for second maximum value from a dictionary, Python

Time:02-02

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]

CodePudding user response:

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

sorted(dic, key=dic.get)[-2] 
  •  Tags:  
  • Related