sorting on keys in a list of dicts

Carl Banks invalidemail at aerojockey.com
Sat Jan 8 01:15:44 EST 2005


Jeff Shannon wrote:
> Jp Calderone wrote:
>
> >     L2 = [(d[key], i, d) for (i, d) in enumerate(L)]
> >     L2.sort()
> >     L = [d for (v, i, d) in L2]
>
> Out of curiosity, any reason that you're including the index?  I'd
> have expected to just do
>
>      L2 = [(d[key], d) for d in L]
>      L2.sort()
>      L = [d for (v, d) in L2]


Suppose L is a list of objects that can't be compared (for example,
they are dicts that have complex number items) and the keys are not all
distinct.  If sort tries to compare two equal keys, it'll proceed to
compare the objects themselves, which could throw an exception.

Stick the index in there, and that possibility is gone.


-- 
CARL BANKS




More information about the Python-list mailing list