我有一个字典列表:
[{'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}]
我想按标题排序,所以带 A 的元素排在 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、title_url,然后是 id?
最佳答案
l.sort(key=lambda x:x['title'])
使用多个键进行排序,假设全部按升序排列:
l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))
关于python - 按字典值对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2878084/