sorting on keys in a list of dicts

Jeff Shannon jeff at ccvcorp.com
Thu Jan 6 16:00:18 EST 2005


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]

I suppose that your version has the virtue that, if the sortkey value 
is equal, items retain the order that they were in the original list, 
whereas my version will sort them into an essentially arbitrary order. 
  Is there anything else that I'm missing here?

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list