使用lambda匿名函数取value进行排序
dic = {'a': 1, 'b': 4, 'c': 2, 'f': 12, 'm': -9}
sort_1 = sorted(dic.items(), key=lambda x: x[1])
sort_2 = sorted(dic.items(), key=lambda x: x[1], reverse=True)
print(sort_1)
print(sort_2)
# [('m', -9), ('a', 1), ('c', 2), ('b', 4), ('f', 12)]
# [('f', 12), ('b', 4), ('c', 2), ('a', 1), ('m', -9)]
使用operator的itemgetter进行排序
import operator
dic = {'a': 1, 'b': 4, 'c': 2, 'f': 12, 'm': -9}
sort_3 = sorted(dic.items(), key=operator.itemgetter(1))
print(sort_3)
# [('m', -9), ('a', 1), ('c', 2), ('b', 4), ('f', 12)]
对于operator的更多内容,请阅读下面的文章
https://www.cnblogs.com/baxianhua/p/8182627.html
将key和value封装成元祖,再进行排序
dic = {'a': 1, 'b': 4, 'c': 2, 'f': 12, 'm': -9}
f = zip(dic.keys(), dic.values())
sort_4 = sorted(f)
print(sort_4)
# [('a', 1), ('b', 4), ('c', 2), ('f', 12), ('m', -9)]