This paper analyzes the method of Python dictionary sorting. Share to everyone for your reference. Specific as follows:
1, the preparation of knowledge:
In Python, dictionary dictionary is a built-in data type, an unordered storage structure, each of which is a Key-value pair:
such as: Dict = {' username ': ' password ', ' database ': ' Master '}, where ' username ' and ' database ' are key, and ' password ' and ' master ' are value, It is possible to obtain a reference to the corresponding value by D[key], but cannot get the key by value.
For dictionnary, you need to know the following considerations:
A, dictionary key is case-sensitive;
b, a dictionary cannot have duplicate key;
C, Dictionary is unordered, there is no concept of element order, they are just the simple arrangement of order pairs.
2, the dictionary sort implementation:
It has been explained that dictionary itself has no sequential concept, but always at some point, but we often need to sort the dictionary, how to do it? Here's what you should know:
Method 1: The simplest method, arrange the elements (Key/value pairs), and then pick out the values. The items method of the dictionary returns a list of tuples with each tuple containing a pair of items-the key and the corresponding value. The sort () method can be sorted at this time.
def sortedDictValues1 (adict): items = Adict.items () items.sort () return [value for key, value in items]
Method 2: Use the arrangement key (key), pick out the value, speed than Method 1 faster. The keys () method of the Dictionary object returns a list of all the key values in the dictionary, in a random order. The sort () method is used whenever sorting is required for the returned list of key values.
def sortedDictValues1 (adict): keys = Adict.keys () keys.sort () return [Adict[key] for key in keys]
Method 3: Use the mapping method to perform the final step more effectively
def sortedDictValues1 (adict): keys = Adict.keys () keys.sort () return map (Adict.get,keys)
Method 4: Sort the dictionary keys, return them in the form of a tuple list, and use the lambda function.
Sorted (iterable[, cmp[, key[, reverse]]
CMP and key typically use lambda
Such as:
>>> d={"OK": 1, "No": 2} #对字典按键排序, return in the form of a tuple list >>> sorted (D.items, Key=lambda d:d[0]) [(' No ', 2), (' OK ', 1) ]
Sorts dictionaries by value and returns them as a tuple list
>>> Sorted (D.items, Key=lambda d:d[1]) [(' OK ', 1), (' No ', 2)]
Although there are many ways to sort the dictionary elements, there is no summary, but if the efficiency of the program is not too high requirements, choose the use of like good.
Hopefully this article will help you with Python programming.