按dict值对dicts列表进行排序

ens*_*are 17 python sorting dictionary

我有一个词典列表:

[{'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}]
Run Code Online (Sandbox Code Playgroud)

我想按标题对它进行排序,所以带有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}]
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?另外,有没有办法确保每个字典键的顺序保持不变,例如,总是标题,title_url,然后是id?

ken*_*ytm 20

l.sort(key=lambda x:x['title'])
Run Code Online (Sandbox Code Playgroud)

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

l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))
Run Code Online (Sandbox Code Playgroud)

  • +1,使用`key`并拉出正确的属性比使用`lambda`作为sort函数更正确/更清晰 (2认同)
  • 是的,我只记得那个--Pix 2.4+有它们,所以它们可能是可用的. (2认同)

ber*_*nie 19

对于那些在被lambdas接近时打喷嚏的人来说,这是一种低过敏性的替代品:

import operator
L.sort(key=operator.itemgetter('title','title_url','id'))
Run Code Online (Sandbox Code Playgroud)


Amb*_*ber 2

调用.sort(fn)列表,其中fn是一个比较标题值并返回比较结果的函数。

mylist.sort(lambda x,y: cmp(x['title'], y['title']))
Run Code Online (Sandbox Code Playgroud)

不过,在 Python 的更高版本(2.4+)中,最好只使用排序键:

mylist.sort(key=lambda x:x['title'])
Run Code Online (Sandbox Code Playgroud)

此外,只要没有更多的添加/删除,字典就保证保持其顺序,如果您迭代键/值的话。但是,如果您添加或删除项目,所有的赌注都会被取消,对此没有任何保证。