sorting a dictionary

Alex Martelli aleax at aleax.it
Tue Feb 4 05:43:09 EST 2003


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:

>>> d={1j:23, 12:15, 7:23}
>>> max([(x[1], x[0]) for x in d.items()])[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot compare complex numbers using <, <=, >, >=
>>>

I have already posted (although not tested) two solutions
that should be immune from this problem because they never
try comparing keys for inequality (only values).  Comparing
items unfortunately may mean comparing keys.

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
code wouldn't be, Andrew, if among the specifications there
was one about keys being guaranteed to be comparable for
inequality), and thus I think the functions I posted earlier
for this task may be preferable.


Alex





More information about the Python-list mailing list