1. 问题:
现有一个列表,需要根据字典元素的某个键,进行排序,该怎样实现?
2. 解决方法:
排序使用sorted函数,通过operator模块中的itemgetter函数实现指定key。
- 示例:
from operator import itemgetter
from pprint import pprint
test_list = [1, 3, 6, 2, 9, 10, 4]
test_dict = [
{"name": "BMW", "price": 20000},
{"name": "Benz", "price": 50000},
{"name": "Audi", "price": 3000},
{"name": "BYD", "price": 1000},
{"name": "CC", "price": 1000},
{"name": "丰田", "price": 9000},
{"name": "保时捷", "price": 600000},
]
sorted_dict_name = sorted(test_dict, key=itemgetter("name"))
sorted_dict_price = sorted(test_dict, key=itemgetter("price"))
sorted_dict = sorted(test_dict, key=itemgetter("price", "name"))
print(f"根据name排序结果:")
pprint(sorted_dict_name)
print(f"根据price字段排序结果:")
pprint(sorted_dict_price)
print(f"根据price字段排序,price相同,再根据name排序结果:")
pprint(sorted_dict)
- 示例结果: