1. 按照字典value排序
student_1={
'a':2,
'b':4,
'c':6,
'd':8
}
student_1_sort = sorted(student_1.iteritems(), 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))
# 单级排序,仅按照score排序
student_2_sort_1 = sorted(student_2, key=lambda e: e.__getitem__('score'))
print "sort by 1 key: ", student_2_sort_1
# 多级排序,先按照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
输出:
original: [{'score': 90, 'no': 1}, {'score': 90, 'no': 2}, {'score': 88, 'no': 3}, {'score': 92, 'no': 4}]
sort by 1 key: [{'score': 88, 'no': 3}, {'score': 90, 'no': 1}, {'score': 90, 'no': 2}, {'score': 92, 'no': 4}]
sort by 2 keys: [{'score': 88, 'no': 3}, {'score': 90, 'no': 1}, {'score': 90, 'no': 2}, {'score': 92, 'no': 4}]
参考这里