Home  >  Article  >  Backend Development  >  Python dictionary (dict) sorted by key and value

Python dictionary (dict) sorted by key and value

高洛峰
高洛峰Original
2017-03-01 14:21:091479browse

The following editor will bring you an article about sorting python dictionaries (dict) by key and value. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

Python The characteristic of dictionary (dict) is that it is unordered. The corresponding value (value) is extracted according to the key (key). If we need the dictionary to be sorted by value, then we can Use the following method to proceed:

1 The following is sorted in order of value from large to small.

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.items(), key=lambda d:d[1], reverse = True)
print(dict)

Output result:

[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]

Let’s break down the code below:

print dic.items() gets a list of [(key, value)].

Then use the sorted method, passing the key parameter, to specify that the sorting is based on value, that is, the value of the first element d[1. reverse = True means that it needs to be flipped. The default is from small to large. If it is flipped, it will be from large to small.

2 Sort the dictionary by key:

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.items(), key=lambda d:d[0]) 
print dict

The above are the python dictionary (dict) keys and sums brought to you by the editor The whole content of value sorting is here. I hope everyone will support the PHP Chinese website~

For more articles related to python dictionary (dict) sorting by key and value, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn