Home >Backend Development >Python Tutorial >python how to sort a list by the values of a dictionary within the list
1. Sort by dictionary value (default is ascending order)
x = {1:2, 3:4, 4 :3, 2:1, 0:0}
1. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1)) print sorted_x
Output result: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
If you want to sort in descending order, you can specify reverse=True
2. sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True) print sorted_x
Output result: [(3, 4), (4, 3), (1, 2), (2 , 1), (0, 0)]
2. Or directly use the reverse method of list to reverse the order of sorted_x
sorted_x.reverse()
3. The more common method is to use lambda expression
sorted_x = sorted(x.iteritems(), key=lambda x : x[1] ) print sorted_x
Output result: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
orted_x = sorted( x.iteritems(), key=lambda x : x[1], reverse=True) print sorted_x
Output result: [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
The above is the detailed content of python how to sort a list by the values of a dictionary within the list. For more information, please follow other related articles on the PHP Chinese website!