sorting a dictionary

Alex Martelli aleax at aleax.it
Tue Feb 4 07:56:54 EST 2003


Andrew Bennetts wrote:

> On Tue, Feb 04, 2003 at 10:43:09AM +0000, Alex Martelli wrote:
>> Andrew Bennetts wrote:
>>    ...
>> > Sure you can... what's wrong with the solution I posted earlier:
>> > 
>> >     max([(x[1], x[0]) for x in d.items()])[1]
>> 
>> This may fail if the dictionary has a complex-number key:
> 
> Heh.  That's a sneaky requirement -- I didn't think of that :)

I was so scatterminded myself on this thread (and on essentialia,
not marginalia...) that I can hardly criticize others!-)


>> You can fix that in various ways, e.g.:
>> 
>> max([(d[k], i, k) for k, i in zip(d,range(len(d))) ])[-1]
>> 
>> but I think this is a bit too complicated for a 1-liner (your
> 
> Indeed :)

Still, the idea is worth noticing: if you want to avoid further
items in a tuple being compared (in a sort, max, etc, on a list
of tuples), process the list to insert an index at the position
right before the further items you don't want to be compared.

The new enumerate built-in in Python 2.3 helps with this, btw:
enumerate(d) does the same job as zip(d, range(len(d))), but
in a faster and more readable way.  Still, I believe it _would_
be still a bit too complicated for a 1-liner, even so.


Alex





More information about the Python-list mailing list