在 Python 中使用值对字典列表进行排序的方法
programmingpythonserver side programming更新于 2025/3/14 17:16:17
在本文中,我们将了解如何使用值对字典列表进行排序。字典表示 Python 中的键-值对,括在花括号中。键是唯一的,冒号将其与值分隔开,而逗号则将项分隔开。这样,冒号前的左侧大小是键,而右侧是其对应的值。
假设我们有以下字典列表 -
[{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
输出应如下 -
Sorted =
[{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]
使用值对字典列表进行排序使用 sorted() 方法中的 lamda 函数
示例
# list of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function print("Sorted = \n",sorted(d, key = lambda item: item['marks']))
输出
Dictionary =
[{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted =
[{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]
使用 sorted() 方法中的 lambda 函数按降序对字典列表进行排序
示例
# List of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function # The reverse parameter is True for Descending Order sort print("Sorted = \n",sorted(d, key = lambda item: item['marks'], reverse = True))
输出
Dictionary =
[{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted =
[{'name': 'Sam', 'marks': 98}, {'name': 'Jacob', 'marks': 97}, {'name': 'Tom', 'marks': 93}]
使用 sorted() 方法中的 itemgetter 方法对字典列表进行排序
示例
from operator import itemgetter # list of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the itemgetter function print("Sorted = \n",sorted(d, key = itemgetter('marks')))
输出
Dictionary =
[{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}]
Sorted =
[{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

