sorting a dictionary

dsavitsk dsavitsk at e-coli.net
Tue Feb 4 13:29:33 EST 2003


There is an irony to my responding too fast and incorrectly as I asked the
same question here

http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&th=2f70b8176dd6dd00&seekm
=mailman.1016053606.7082.python-list%40python.org&frame=off


"Laura Creighton" <lac at strakt.com> wrote in message
news:mailman.1044345130.23490.python-list at python.org...
> > 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