Sorting a dictionary

François Pinard pinard at iro.umontreal.ca
Wed Mar 15 08:13:30 EST 2000


Mikael Olofsson <mikael at isy.liu.se> writes:

> On 13-Mar-00 Alex wrote:
>  >  l = map (None, mydict.values (), mydict.keys ())
>  >  l.sort ()
>  >  l.reverse ()

> What's wrong with 

> l=mydict.items()

This would give (key,value) pairs, while one needs (value,key) pairs.
The idea is to sort on the value as the primary key.

I wonder a bit, however.  The Library Reference says that for mydict.keys(),
mydict.values() and mydict.items(), "Keys and values are listed in random
order".  The above solution only works if the _same_ random order is used for
both keys and values.  It is very reasonable to imagine the implementation
is such that the random order is the same, but the specification does not
promise it.  So, even if elegant, the solution above might be wrong from
a theoretical standpoint.

Could the documentation of Python be modified to clarify this point,
in one way or another?

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard






More information about the Python-list mailing list