Python's sorted function sorts dictionaries by key and value

Python's sorted function sorts dictionaries by key and value

1.sorted function sorts dictionary by key value

    First, let's briefly introduce the sorted function, sorted(iterable, key, reverse), sorted has three parameters: iterable, key, and reverse.

    where iterable represents an object that can be iterated, such as dict.items(), dict.keys(), etc. key is a function used to select the elements involved in the comparison, reverse is used to specify whether the sorting is reverse or sequential, reverse =true is the reverse order, reverse=false is the order, and the default is reverse=false.

    To sort a dictionary by key value, you can use the following statement:

    

    Use sorted(d.keys()) directly to sort the dictionary by key value. Here, the key value is sorted in order. If you want to sort in reverse order, you only need to set reverse to true.

2. The sorted function sorts the dictionary by value

    To sort the value of the dictionary, you need to use the key parameter. Here we mainly provide a method using lambda expressions, as follows:

     

The d.items() here is actually converting d to an iterable object, and the elements of the iterable object are ('lilee', 25), ('wangyan', 21), ('liqun', 32), ('lidaming' ',19), the items() method converts the elements of the dictionary into tuples, and the lambda expression corresponding to the key parameter here means to select the second element in the tuple as the comparison parameter (if you write key=lambda item :item[0] is to select the first element as the comparison object, that is, 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 using this method can Sort the values ​​of the dictionary. Note that the sorted return value is a list, and the name-value pairs in the original dictionary are converted into tuples in the list.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325693022&siteId=291194637