python 按字典value排序以及按list中字典的某个key的value排序
1. 按照字典value排序
student_1={'a':2,'b':4,'c':6,'d':8}
student_1_sort = sorted(student_1.items(), key=lambda d: d[1], reverse=True)
print(student_1_sort)
输出:
[('d', 8), ('c', 6), ('b', 4), ('a', 2)]
2. 按list中字典的某个key的value排序
student_2 = [
{"no": 1, "score": 90},
{"no": 2, "score": 90},
{"no": 3, "score": 88},
{"no": 4, "score": 92},
]
print("original: {0}".format(student_2))
输出:
original: [{'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 3, 'score': 88}, {'no': 4, 'score': 92}]
# 单级排序,仅按照score排序
student_2_sort_1 = sorted(student_2, key=lambda e: e.__getitem__('score'))
print("sort by 1 key: ", student_2_sort_1)
输出:
sort by 1 key: [{'no': 3, 'score': 88}, {'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 4, 'score': 92}]
# 多级排序,先按照score,再按照no排序
student_2_sort_2 = sorted(student_2, key=lambda e:(e.__getitem__('score'), e.__getitem__('no')))
print("sort by 2 keys: ", student_2_sort_2)
输出:
sort by 2 keys: [{'no': 3, 'score': 88}, {'no': 1, 'score': 90}, {'no': 2, 'score': 90}, {'no': 4, 'score': 92}]
作者:DreamLee0625
来源:CSDN
原文:https://blog.csdn.net/vitaminc4/article/details/78791437
版权声明:本文为博主原创文章,转载请附上博文链接!