Home > Backend Development > Python Tutorial > How to sort python dictionary by value

How to sort python dictionary by value

silencement
Release: 2019-07-08 10:19:43
Original
7272 people have browsed it

How to sort python dictionary by value

sorted function

First introduce the sorted function, sorted (iterable, key, reverse), sorted has three types: iterable, key, reverse parameters.

Iterable represents an object that can be iterated, such as dict.items(), dict.keys(), etc. key is a function used to select the elements participating in the comparison, and reverse is used to specify the sorting Is it in reverse order or order? reverse=true means reverse order (from large to small), reverse=false means order (from small to large), and the default is reverse=false.

Sort by value

There are three ways to sort the dictionary by value

key uses the lambda anonymous function to take the value and sort it

d = {'lilee':25, 'wangyan':21, 'liqun':32, 'age':19}
sorted(d.items(), key=lambda item:item[1])
Copy after login

The output result is

[('age',19),('wangyan',21),('lilee',25),('liqun',32)]
Copy after login
Copy after login
Copy after login

If you need to reverse the order, the result obtained by

sorted(d.items(), key=lambda item:item[1], reverse=True)
Copy after login

will be

[('liqun',32),('lilee',25),('wangyan',21),('age',19)]
Copy after login

using the operator itemgetter sorts

import operator
sorted(d.items(), key=operator.itemgetter(1))
Copy after login

The output result is

[('age',19),('wangyan',21),('lilee',25),('liqun',32)]
Copy after login
Copy after login
Copy after login

Divide the key and value into tuples, and then sort them

f = zip(d.keys(), d.values())
c = sorted(f)
Copy after login

The output result is

[('age',19),('wangyan',21),('lilee',25),('liqun',32)]
Copy after login
Copy after login
Copy after login

The above is the detailed content of How to sort python dictionary by value. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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