This article analyzes the method of sorting Python dictionaries. Share to everyone for your reference. Specifically as follows:
1, the preparation of knowledge:
In Python, the dictionary dictionary is a built-in data type, an unordered storage structure, and each element is a Key-value pair:
such as: Dict = {' username ': ' password ', ' database ': ' Master '}, where ' username ' and ' database ' are key, and ' password ' and ' master ' are value, You can get a reference to the value by D[key], but you cannot get the key by value.
For dictionnary, you should be aware of the following considerations:
A, dictionary's key is case sensitive;
b, a dictionary can not have duplicate key;
C, dictionary are unordered, without the concept of element order, they are just the simple arrangement of the order pairs.
2, Dictionary sorting implementation:
As explained earlier, dictionary does not have a sequential concept in itself, but always at some point, but we often need to sort the dictionary, how do we do it?
Method 1: The simplest way to arrange the elements (Key/value pairs) and then pick out the values. The items method of the dictionary returns a list of tuples in which each tuple contains a pair of items-the key and the corresponding value. The sort () method can be sorted at this time.
?
1 2 3 4 |
def sortedDictValues1 (adict): items = Adict.items () items.sort () return [value for key, value in items] |
Method 2: Use the permutation key (key) way, pick out the value, speed is faster than Method 1. The Dictionary object's keys () method returns a list of all the key values in the dictionary, in a random order. You need to sort by using the sort () method on the returned list of key values.
?
1 2 3 4 |
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
?
1 2 3 4 |
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 a lambda function.
Sorted (iterable[, cmp[, key[, reverse]]]
CMP and key generally use lambda
Such as:
?
1 2 3 |
>>> 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) ] |
Sort the dictionary by value and return it in the form of a tuple list
?
1 2 |
>>> 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 of the whole, but if the program efficiency is not too high, choose to like the use of good.
I hope this article will help you with your Python programming.