转自https://blog.csdn.net/Thomas0713/article/details/83028414
1 2 3 4 5 6 7 8 9 10 11 12 13
| x = [{'a': 3}, {'b': 1}, {'c': 5}]
list_a = [] # 初始化一个列表 for i in x: # 遍历列表中的字段 for j in i.keys(): # 取出key list_a += {j: i[j]}.items() # 把字典转换成元组 aa = sorted(list_a, key=lambda value: value[1]) # 对列表中的元组排序
list_b = [{i[0]: i[1]} for i in aa] # 把元组再转换成字典 print(list_b) #######################################
[{'b': 1}, {'a': 3}, {'c': 5}]
|
等同于
1 2 3 4 5 6 7 8 9
| x = [{'a': 3}, {'b': 1}, {'c': 5}]
list_a = sorted({j: i[j] for i in x for j in i.keys()}.items(), key=lambda value: value[1])
list_b = [{i[0]: i[1]} for i in list_a] print(list_b) #######################################
[{'b': 1}, {'a': 3}, {'c': 5}]
|
以下转自https://www.runoob.com/python3/python3-func-sorted.html
1 2 3 4 5
| array = [{"age":20,"name":"a"},{"age":25,"name":"b"},{"age":10,"name":"c"}] array = sorted(array,key=lambda x:x["age"]) print(array) ################################ [{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
|
1 2 3 4 5 6 7 8 9
| #先按照成绩降序排序,相同成绩的按照名字升序排序:
d1 = [{'name':'alice', 'score':38}, {'name':'bob', 'score':18}, {'name':'darl', 'score':28}, {'name':'christ', 'score':28}] l = sorted(d1, key=lambda x:(-x['score'], x['name'])) print(l)
############################################
[{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]
|