sorting on keys in a list of dicts

Scott David Daniels Scott.Daniels at Acm.Org
Fri Jan 7 18:39:02 CET 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?

Others have already remarked that this preserves sort stability
(which is, in fact a lovely property).  There is another property
which hasn't been mentioned:
     As written, only the key and the index are compared.

Try sorting:
     tricky = [dict(a=5j, b=1), dict(a=4j, b=1)]
     similar = [(5j, 1), (4j, 1)]

without the index.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list