Home  >  Article  >  Backend Development  >  How to sort python dictionary by value

How to sort python dictionary by value

silencement
silencementOriginal
2019-06-26 13:52:557015browse

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])

The output result is

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

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

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

will be

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

using the operator itemgetter sorts

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

The output result is

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

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

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

The output result is

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

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!

Statement:
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