sorting a dictionary
Laura Creighton
lac at strakt.com
Tue Feb 4 02:42:30 EST 2003
> def get_highest(d): # don't use the name 'dict'
> l = d.keys()
> l.sort()
> return l[-1]
>
> -d
If you give this a dict of d1={"a":10, "b":5, "c":15, "d":12}
this will return 'd' because 'd' sorts after 'c'. I don't
think that this is what the OP wanted.
This will work, but there may be faster ways.
>>> def get_highest(d):
... l = []
... for k in d.keys():
... l.append([d[k], k])
... l.sort()
... return l[-1][1]
...
>>> get_highest(d1)
'c'
Laura
>
> "Yuval" <yuvalfeld at hotmail.com> wrote in message
> news:6ca96053.0302032256.63f147be at posting.google.com...
> > 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.
> >
> > Thanks.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list