1. Sort by dictionary 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)
Output:
[(' d ', 8), (' C ', 6), (' B ', 4), (' A ', 2)]
2. Sort by value of a key in the dictionary in list
Student_2 = [
{
"no": 1,
"score": +
},
{
"no": 2,
"score": M
},
{
"no": 3,< c10/> "Score": "The Next"
,
{
"no": 4,
"score": I
},
]
print ("original: {0}". Format ( student_2))
# Single order, sorted by score only
student_2_sort_1 = sorted (student_2, Key=lambda e:e.__getitem__ (' score '))
print "Sort by 1 key:", student_2_sort_1
# Multi-level sorting, followed by score, then sorted by 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
Output:
Original: [{' Score ': The ' no ': 1}, {' Score ': #, ' No ': 2}, {' score ': +, ' no ': 3}, {' Score ': $, ' No ': 4}]
Sort by 1 Key: [{' Score ': The ' No ': 3}, {' Score ': #, ' No ': 1}, {' Score ': #, ' No ': 2}, {' Score ': $, ' No ': 4}]
Sort by 2 Keys: [{' score ': +, ' no ': 3}, {' Score ': #, ' No ': 1}, {' Score ': #, ' No ': 2}, {' Score ': $, ' No ': 4}]
Reference here