Sorting a list of objects by multiple attributes

Kent Johnson kent at kentsjohnson.com
Tue Apr 11 07:02:33 EDT 2006


gry at ll.mit.edu wrote:
> For multiple keys the form is quite analogous:
> 
>    L.sort(key=lambda i: (i.whatever, i.someother, i.anotherkey))
> 
> I.e., just return a tuple with the keys in order from your lambda.
> Such tuples sort nicely.  

In Python 2.5 you can do this with operator.attrgetter():

   L.sort(key=operator.attrgetter('whatever', 'someother', 'anotherkey'))

Kent



More information about the Python-list mailing list