ksc*_*ler 3 python sorting dictionary list
我只想在python中按first_name排序这个列表
list = [ { "profile" : { "first_name" : "a", "last_name" : "b" } } ,
{ "profile" : { "first_name" : "c", "last_name" : "d" } } ,
{ "profile" : { "first_name" : "e", "last_name" : "f" } } ]
Run Code Online (Sandbox Code Playgroud)
这应该这样做:
>>> sorted(lst, key=lambda x: x['profile']['first_name'])
Run Code Online (Sandbox Code Playgroud)
要对列表本身进行排序,请使用:
lst.sort(key=lambda x: x['profile']['first_name'])
Run Code Online (Sandbox Code Playgroud)
要保持lst未排序并返回已排序的列表,请使用:
sorted(lst, key=lambda x: x['profile']['first_name'])
Run Code Online (Sandbox Code Playgroud)