sorting a dictionary

Andrew Bennetts andrew-pythonlist at puzzling.org
Tue Feb 4 10:53:33 CET 2003


On Tue, Feb 04, 2003 at 09:30:48AM +0000, Alex Martelli wrote:
> Alex Martelli wrote:
> 
> > dsavitsk wrote:
> > 
> > [about getting the largest key -- the "sorting" in the subject
> > is a bit of involuntary misdirection by the OP...:-)]
> > 
> >> def get_highest(d): # don't use the name 'dict'
> >>     l = d.keys()
> >>     l.sort()
> >>     return l[-1]
> > 
> > This is good, but it's O(N logN) -- if the dictionary is
> > huge, you'll be hurting.  max(d) is faster, and follows
> > the good rule of not reimplementing something that Python
> > already has as a built-in.
> 
> Heh -- sorry, I see the OP wanted the *key of the highest
> value*, NOT the highest key, which is what dsavitsk's
> solution, and max(d), would give.  For the OP's problem,
> you can't get any faster than O(N logN).

Sure you can... what's wrong with the solution I posted earlier:

    max([(x[1], x[0]) for x in d.items()])[1]

?

[Besides being a gratuitous one-liner <wink>]

-Andrew.






More information about the Python-list mailing list