sorting a dictionary

Nick Vargish nav at adams.patriot.net
Tue Feb 4 12:42:34 EST 2003


yuvalfeld at hotmail.com (Yuval) writes:

> I'm looking for an efficient way to get the key of the highest value
> in a dictionary.
> For example, for dict = {"a":10, "b":5, "c":15}, I want to write a
> function get_highest(dict), that will return c as the result (since c
> is the key of the highest value in the dict.

def key_of_highest(d):
    mv = max(d.values())
    for k in d:
        if d[k] == mv:
            break
    return k

Well, it may not be O(N), but it avoids spurious assignments. :^)

Nick

-- 
# sigmask.py  ||  version 0.2  ||  2003-01-07  ||  Feed this to your Python.
print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','')





More information about the Python-list mailing list