sorting a dictionary

John La Rooy nospampls.jlr at doctor.com
Tue Feb 4 15:30:51 EST 2003


On 04 Feb 2003 12:42:34 -0500
Nick Vargish <nav at adams.patriot.net> wrote:

> 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
> 
It is O(N)

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

John




More information about the Python-list mailing list