views:

167

answers:

4

I have a list of dictionaries:

[{'title':'New York Times', 'title_url':'New_York_Times','id':4},
 {'title':'USA Today','title_url':'USA_Today','id':6},
 {'title':'Apple News','title_url':'Apple_News','id':2}]

I'd like to sort it by the title, so elements with A go before Z:

[{'title':'Apple News','title_url':'Apple_News','id':2},
 {'title':'New York Times', 'title_url':'New_York_Times','id':4},
 {'title':'USA Today','title_url':'USA_Today','id':6}]

What's the best way to do this? Also, is there a way to ensure the order of each dictionary key stays constant, e.g., always title, title_url, then id?

A: 

Call .sort(fn) on the list, where fn is a function which compares the title values and returns the result of the comparison.

mylist.sort(lambda x,y: cmp(x['title'], y['title']))

In later versions of Python, though (2.4+), it's much better to just use a sort key:

mylist.sort(key=lambda x:x['title'])

Also, dictionaries are guaranteed to keep their order, were you to iterate through keys/values, as long as there are no more additions/removals. If you add or remove items, though, all bets are off, there's no guarantee for that.

Amber
A: 
originalList.sort(lambda d1, d2: cmp(d1['title'], d2['title']))

Though this only sorts on title and order after that is undefined. Doing multiple levels would be painful this way.

Daniel DiPaolo
`cmp` is deprecated with good reason as `key` is much better. Sorting on multiple levels is easy - just use tuples see Kenny's answer
gnibbler
The order after that is defined as the order in which they originally occurred. (Python sorts are stable.)
Mike Graham
+7  A: 
l.sort(key=lambda x:x['title'])

To sort with multiple keys, assuming all in ascending order:

l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))
KennyTM
+1, using `key` and pulling the proper attribute is more correct/cleaner than just using a `lambda` as the sort function
Daniel DiPaolo
Yeah, I just remembered that as well - Python 2.4+ has them, so they're probably available.
Amber
+9  A: 

The hypoallergenic alternative for those who sneeze when approached by lambdas:

import operator
L.sort(key=operator.itemgetter('title','title_url','id'))
Adam Bernier