Home > Backend Development > Python Tutorial > How to sort a dictionary by its value (key)

How to sort a dictionary by its value (key)

anonymity
Release: 2019-05-27 14:02:31
Original
8002 people have browsed it

sorted function

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

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.

How to sort a dictionary by its value (key)

Sort by key

To sort the dictionary by key, you can call the sorted function directly.

my_dict = {'lilee':25, 'age':24, 'phone':12}
sorted(my_dict.keys())
Copy after login

The output result is

['age', 'lilee', 'phone']

Use sorted(my_dict.keys()) directly to press the key value To sort the dictionary, here the key values ​​are sorted in order. If you want to sort in reverse order, you only need to set reverse to true.

sorted(my_dcit.keys(), reverse = true)

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

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