对字典进行排序是不可能的,只有把字典转换成另一种方式才能排序。字典本身是无序的,但是像列表、元祖等其他类型是有序的。所以需要一个元祖列表来表示排序的字典
DEMO:
import operator x = {1: 2, 3: 4, 4:3, 2:1, 0:0} sorted_x = sorted(x.items(), key=operator.itemgetter(1))
也可以:
sorted(d.items(), key=lambda x: x[1])
Last updated 5 years ago
Was this helpful?