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.
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!