在Python中按值对字典列表进行排序的方法——使用 lambda函数
在日常编程中,排序一直是一个有用的工具。 Python中的字典广泛用于从竞争领域到开发者领域的许多应用程序(例如处理 JSON 数据)。在这种情况下,拥有根据值对字典进行排序的知识可能会很有用。
有两种方法可以实现这种排序:
1.)使用 lambda函数:-
本文处理使用 lambda函数和使用“ sorted() ”内置函数进行排序。还可以实现各种变体来对字典进行排序。
- 对于降序:除了 sorted()函数之外,还使用“ reverse = True ”。
- 对于对多个值进行排序:用“逗号”分隔,指出必须执行排序的正确顺序。
Python3
# Python code demonstrate the working of
# sorted() with lambda
# Initializing list of dictionaries
lis = [{ "name" : "Nandini", "age" : 20},
{ "name" : "Manjeet", "age" : 20 },
{ "name" : "Nikhil" , "age" : 19 }]
# using sorted and lambda to print list sorted
# by age
print ("The list printed sorting by age: ")
print (sorted(lis, key = lambda i: i['age']))
print ("\r")
# using sorted and lambda to print list sorted
# by both age and name. Notice that "Manjeet"
# now comes before "Nandini"
print ("The list printed sorting by age and name: ")
print (sorted(lis, key = lambda i: (i['age'], i['name'])))
print ("\r")
# using sorted and lambda to print list sorted
# by age in descending order
print ("The list printed sorting by age in descending order: ")
print (sorted(lis, key = lambda i: i['age'],reverse=True))
输出:
The list printed sorting by age:
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}]
The list printed sorting by age and name:
[{'age': 19, 'name': 'Nikhil'}, {'age': 20, 'name': 'Manjeet'}, {'age': 20, 'name': 'Nandini'}]
The list printed sorting by age in descending order:
[{'age': 20, 'name': 'Nandini'}, {'age': 20, 'name': 'Manjeet'}, {'age': 19, 'name': 'Nikhil'}]