简体   繁体   中英

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

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]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM