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

How to sort a dictionary by its value (key)

anonymity
anonymityOriginal
2019-05-27 14:02:317812browse

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

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!

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