A brief discussion on sorting python dictionary (dict) by key and value

 

The following editor will bring you a python dictionary (dict) sorting by key and value. The editor thinks it is pretty good, and I will share it with you now, and also give you a reference. Let’s follow the editor of Weidian Reading to take a look.

The characteristic of python 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, we can use the following method:

1 The following are sorted according to the order of value from large to small.

1

2

3

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:

1

[('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, through 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 reversed. The default is from small to large. If it is reversed, it is from large to small.

2 Sort the dictionary by key:

1

2

3

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 is the whole content of sorting the keys and values ​​of the python dictionary (dict) brought to you by the editor, I hope it can help you!

Reprinted from: Weidian Reading    https://www.weidianyuedu.com

Guess you like

Origin blog.csdn.net/weixin_45707610/article/details/131768399