ensnare
ensnare

Reputation: 42013

Sort a list of dicts by dict values

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?

Upvotes: 17

Views: 10170

Answers (4)

mechanical_meat
mechanical_meat

Reputation: 169274

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

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

Upvotes: 19

Amber
Amber

Reputation: 526523

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.

Upvotes: 2

kennytm
kennytm

Reputation: 523174

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']))

Upvotes: 20

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

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.

Upvotes: -1

Related Questions