python dict根据key和value排序

根据key排序

a = {'a':1, 'c':2, 'b':3}
[(k,a[k]) for k in sorted(a.keys())]
#返回 [('a', 1), ('b', 3), ('c', 2)]

 根据value排序

a = {'a':1, 'c':2, 'b':3}
sorted(a.items(), key=lambda d:d[1], reverse = True)

 #返回list:[('b', 3), ('c', 2), ('a', 1)]

猜你喜欢

转载自heipark.iteye.com/blog/2357087