Use operator.itemgetter () and sorted () to sort the dictionary

operator.itemgetter () function is used to obtain the element from the object, a simple example

import operator
import numpy
get = operator.itemgetter(0)

# 相当于x[0]. 
x = numpy.array([1,2,3,4])
get(x)
>>> 1

# 相当于y[0]. 
y = numpy.array([[1,2,3,4],[5,6,7,8]])
get(y)
>>> array([1, 2, 3, 4])

Sort the dictionary

import operator
z = {'A':8, 'C':5, 'B':3}

get = operator.itemgetter(0) # 按字典的键排序
zsort = sorted(z.items(), key=get, reverse=False)
print(zsort)
>>> [('A', 8), ('B', 3), ('C', 5)]

get = operator.itemgetter(1) # 按字典的值排序
zsort = sorted(z.items(), key=get, reverse=False)
print(zsort)
>>> [('B', 3), ('C', 5), ('A', 8)]
Published 34 original articles · won praise 3 · Views 1292

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/104835875