sorting a dictionary

Terry Reedy tjreedy at udel.edu
Tue Feb 4 15:57:44 EST 2003


"Nick Vargish" <nav at adams.patriot.net> wrote in message
news:yyyof5sj62d.fsf at adams.patriot.net...
> 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. :^)

It is O(n) (assuming that d.values() is); there is only the matter of
the constant, and the space for d.values() (versus the iterator
version).

TJR






More information about the Python-list mailing list