python how to sort a list by the values ​​of a dictionary within the list

silencement
Release: 2019-05-25 16:21:18
Original
17205 people have browsed it

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!