[Reprinted] the python sorted function sorts the dictionary by key and value, and pythonsorted
1. Sort the sorted function by key value to the dictionary
First, we will introduce the sorted function, sorted (iterable, key, reverse). sorted has three parameters: iterable, key, and reverse.
Iterable indicates objects that can be iterated, for example, dict. items (), dict. keys () and so on. The key is a function used to select the elements involved in the comparison. The reverse is used to specify whether the sorting is reverse or backward, and the reverse = true is reverse, if reverse is set to false, the order is displayed. The default value is reverse = false.
To sort the dictionary by key value, you can use the following statement:
Directly use sorted (d. keys () can be sorted by the key value pairs in the dictionary. Here, the key value is sorted by order. If you want to sort the key value in reverse order, you only need to set the reverse to true.
2. Sort the sorted function by value to the dictionary
The key parameter is required for sorting the value of the dictionary. Here we mainly provide a method to use lambda expressions, as follows:
D. items () is actually to convert d to an iterative object. The elements of the iteration object are ('lile', 25), ('wangyan ', 21), ('liqun', 32), ('canonicalization', 19), the items () method converts the dictionary elements into tuples, here, the lambda expression corresponding to the key parameter means to select the second element in the tuples as the comparison parameter (if the key = lambda item is written: item [0] selects the first element as the comparison object, that is, the key value as the comparison object. In lambda x: y, x indicates the output parameter, and y indicates the return value of the lambda function. Therefore, this method can be used to sort the dictionary values. Note that the returned value after sorting is a list, and the name-value pairs in the original dictionary are converted to the tuples in the list.