Sort a list of dicts by dict values

久未见 提交于 2020-01-10 12:53:06

问题


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?


回答1:


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



回答2:


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

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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2878084/sort-a-list-of-dicts-by-dict-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!