python中的字典非常常用,它本身是无序的,但有时我们需要对字典排序,下面记录一下分别按照key排序和按照值排序
sorted中 reverse = True 表示倒序
情况一:只有一个value
dic={"a":1,"b":3,"c":5,"d":2}
#按照键排序
sorted(dic.items(),key=lambda d:d[0])
[('a', 1), ('b', 3), ('c', 5), ('d', 2)]
#按照值排序
sorted(dic.items(),key=lambda d:d[1])
[('a', 1), ('d', 2), ('b', 3), ('c', 5)]
b = {1:7,2:4,5:6}
sorted(b.items(),key = lambda x :x[1],reverse = True)
[(1, 7), (5, 6), (2, 4)]
其中d[0]表示键,d[1]表示value
情况二:多重嵌套字典排序,排序为升序排序,结果为一个嵌套元组构成的列表
dic={"a":{"a1":3,"a2":7},"b":{"a1":1,"a2":8},"c":{"a1":5,"a2":9}}
sorted(dic.items(),key=lambda d:d[1]["a1"])
[('b', {'a2': 8, 'a1': 1}), ('a', {'a2': 7, 'a1': 3}), ('c', {'a2': 9, 'a1': 5})]
sorted(dic.items(),key=lambda d:d[1]["a2"])
[('a', {'a2': 7, 'a1': 3}), ('b', {'a2': 8, 'a1': 1}), ('c', {'a2': 9, 'a1': 5})]
来源:https://blog.csdn.net/ccmhzl/article/details/100085815