使用 itemgetter 在 Python 中按值对字典列表进行排序的方法
当需要根据值对字典列表进行排序时,可以使用itemgetter属性。
以下是相同的演示-
示例
from operator import itemgetter my_list = [{ "name" : "Will", "age" : 56}, { "name" : "Rob", "age" : 20 }, { "name" : "Mark" , "age" : 34 }, { "name" : "John" , "age" : 24 }] print("按年龄排序的列表是: ") print(sorted(my_list, key=itemgetter('age'))) print("按年龄和姓名排序的列表是: ") print(sorted(my_list, key=itemgetter('age', 'name'))) print("按年龄降序排列的列表是: ") print(sorted(my_list, key=itemgetter('age'),reverse = True))输出结果
按年龄排序的列表是: [{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will', 'age': 56}] 按年龄和姓名排序的列表是: [{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will', 'age': 56}] 按年龄降序排列的列表是: [{'name': 'Will', 'age': 56}, {'name': 'Mark', 'age': 34}, {'name': 'John', 'age': 24}, {'name': 'Rob', 'age': 20}]
解释
导入所需的包。
字典元素列表已定义并显示在控制台上。
使用sorted方法,键指定为“itemgetter”。
字典列表再次使用itemgetter作为两个参数进行排序。
输出显示在控制台上。