sorting a dictionary

Giles Brown giles_brown at hotmail.com
Tue Feb 4 08:34:24 EST 2003


Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote in message news:<mailman.1044344708.2460.python-list at python.org>...
> On Mon, Feb 03, 2003 at 10:56:20PM -0800, Yuval wrote:
> > I'm looking for an efficient way to get the key of the highest value
> > in a dictionary.
> 
> def get_highest(d):
>     return max([(x[1], x[0]) for x in d.items()])[1]
> 
> Tested:
> 
>     >>> def get_highest(d):
>     ...     return max([(x[1], x[0]) for x in d.items()])[1]
>     ... 
>     >>> get_highest({"a":10, "b":5, "c":15})
>     'c'

I like this approach.  It seems very clear to me.
Just for curiosity I though I might write a version using generators.
(Playing with new toys I guess.)

from __future__ import generators

def iteritemsvk(d):
    iterator = d.iteritems()
    while 1:
        k, v = iterator.next()
        yield (v, k)

def get_highest(d):
    return max(iteritemsvk(d))[1]

d = { "a" : 10, "b" : 5, "c" : 15 }
print get_highest(d)

Less compact than Andrew's answer, the only possible advantage I
could see to this approach is avoiding creating a full list of
key, value pairs (which might be a problem if the dictionary had
a lot in it).  Am I right in thinking this avoids creating a list?

Cheers,
Giles




More information about the Python-list mailing list