The following small series will bring you a python dictionary (dict) key and value sorting. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at the following small series to bring you a python dictionary (dict) key and value sorting. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.
The characteristics of the python dictionary (dict) are unordered. the corresponding values are extracted by key. if we need to sort the dictionary by value, you can use the following method:
1. values are sorted in the ascending order of values.
Dic = {'a': 31, 'BC': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D ': 0} dict = sorted (dic. items (), key = lambda d: d [1], reverse = True) print (dict)
Output result:
[('A', 74), ('A', 31), ('BC', 5), ('asd ', 4), ('C ', 3), ('D', 0)]
The following code is broken down:
Print dic. items () to obtain the [(key, value)] list.
Then, use the sorted method and the key parameter to specify that the sorting is based on the value, that is, the value of the first element d [1. Reverse = True indicates that the system needs to be flipped. the default value is from small to large. if it is flipped, it is from large to small.
2 pairs of dictionary key sorting:
Dic = {'a': 31, 'BC': 5, 'C': 3, 'asd ': 4, 'A': 74, 'D ': 0} dict = sorted (dic. items (), key = lambda d: d [0]) print dict
The above is all the python dictionary (dict) keys and values sorted by the editor. I hope you can support PHP ~
For more python dictionary (dict) key-value sorting articles, refer to PHP Chinese network!