使用python中的值对字典列表进行排序的方法
在本文中,您将学习如何使用Python中的值对字典列表进行排序。我们将使用内置的方法调用分类排序的字典。
字典排序步骤
我们将按照下面提到的步骤使用值对字典进行排序。
将包含字典和键的列表传递给已排序的方法。
1.使用lambda函数
2.使用itemgetter方法
我们可以通过两种不同的方式传递键
让我们看看例子。
1.使用lambda函数
示例
## list of dictionaries
dicts = [
{"name" : "John", "salary" : 10000},
{"name" : "Emma", "salary" : 30000},
{"name" : "Harry", "salary" : 15000},
{"name" : "Aslan", "salary" : 10000}
]
## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = lambda item: item['salary']))如果您运行上述程序,我们将得到以下结果。
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]2.使用itemgetter方法
使用itemgetter对字典进行排序的过程与上述过程相似。我们使用itemgetter方法将值传递给键,这是唯一的区别。让我们来看看。
示例
## importing itemgetter from the operator
from operator import itemgetter
## list of dictionaries
dicts = [
{"name" : "John", "salary" : 10000},
{"name" : "Emma", "salary" : 30000},
{"name" : "Harry", "salary" : 15000},
{"name" : "Aslan", "salary" : 10000}
]
## sorting the above list using 'lambda' function
## we can reverse the order by passing 'reverse' as 'True' to 'sorted' method
print(sorted(dicts, key = itemgetter('salary')))输出结果
如果您运行上述程序,我们将得到以下结果。
[{'name': 'John', 'salary': 10000}, {'name': 'Aslan', 'salary': 10000}, {'name': 'Harry', 'salary': 15000}, {'name': 'Emma', 'salary': 30000}]热门推荐
10 新年友情祝福语 简短独特
11 结婚给姐妹祝福语简短
12 车行销售祝福语简短
13 同事有趣祝福语大全简短
14 离职横幅升职祝福语简短
15 爸爸过年的祝福语简短
16 岳母娘生日祝福语简短
17 周年庆典祝福语致辞简短
18 妹妹住院祝福语简短英文