1.sorted functions sort the dictionary by key value
First of all, the basic introduction of the sorted function, sorted (iterable,key,reverse), sorted have iterable,key,reverse these three parameters.
Where iterable represents an object that can be iterated, such as Dict.items (), Dict.keys (), and so on, the key is a function that selects the elements that participate in the comparison, and reverse is used to specify whether the sort is reversed or sequential, reverse= True is reverse, reverse=false is the order, default is Reverse=false.
To sort the dictionary by key value, you can use the following statement:
Directly using sorted (D.keys ()) You can sort the dictionary by key value, where you sort the key values in order, and if you want to sort by reverse, just place the reverse as true.
2.sorted function to sort dictionaries by value value
To sort the value of a dictionary, you need a key parameter, which provides a way to use a lambda expression, as follows:
The D.items () here is actually converting D to an iterative object, the elements of the Iteration object are (' Lilee ', 25), (' Wangyan ', 21), (' Liqun ', 32), (' lidaming ', '), the items () method converts the elements of the dictionary Converted to tuples, and here the key parameter's lambda expression means to select the second element in the tuple as the comparison parameter (if writing KEY=LAMBDA item:item[0] then select the first element as the comparison object, the key value as the comparison object. In Lambda X:y, x represents the output parameter, and Y represents the return value of the lambda function, so this method can be used to sort the value of the dictionary. Note that the sorted return value is a list, and the name value pairs in the original dictionary are converted to tuples in the list.