Thread: A sort question
View Single Post
Old Mar 25th, 2008, 8:56 AM   #2
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Posts: 1,799
Rep Power: 5 Sane will become famous soon enough
Re: A sort question

Sure thing. Just use a lambda function as a sort callback to the .sort() method.

Lambda functions allow you to pass a function as an argument. You could also create a function with def, and pass that through, but it's not as fancy.

This is according to your example, where each dictionary always has one item. If it doesn't always have one item, you will have to do some sort of nested sort according to more specific requirements.

>>> foo = [ {'a':[7,8,9]}, {'b':[4,5,6]}, {'c':[1,2,3]}, {'d':[0,4,10]} ]
>>> foo.sort(lambda x,y: x.values()[0][1]-y.values()[0][1])
>>> foo
[{'c': [1, 2, 3]}, {'d': [0, 4, 10]}, {'b': [4, 5, 6]}, {'a': [7, 8, 9]}]

I'm not sure how much gibberish I'm spouting, so if you need me to explain sort callbacks or lambda functions, just ask.
Sane is offline   Reply With Quote