简体   繁体   中英

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, eg, always title, title_url, then id?

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

要使用多个键进行排序,请按升序排列:

l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM