按dict值排序一个列表 [英] Sort a list of dicts by dict values
本文介绍了按dict值排序一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典列表:
[{'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}]
d喜欢按标题排序,所以元素与A之前Z:
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}]
最好的方法是什么?
另外,有没有办法确保每个字典键的顺序保持不变,例如,总是标题,title_url,然后是id?
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?
推荐答案
对于那些在lambdas接近的时候打喷嚏的人,低过敏原的选择:
The hypoallergenic alternative for those who sneeze when approached by lambdas:
import operator
L.sort(key=operator.itemgetter('title','title_url','id'))
这篇关于按dict值排序一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文