Python中对字典排序

来源:互联网 发布:拓扑学 网络课程 编辑:程序博客网 时间:2024/05/20 20:44

python中对字典的排序,默认是按照key来排序的,有时候会用到用value来排序

使用sorted函数可以对list或者iterator进行排序,举个��:sorted(iterable[, cmp[, key[, reverse]]])

a={1:'b',2:'a',3:'c'}

In [28]:sorted(a.items())

Out[28]:[(1, 'b'), (2, 'a'), (3, 'c')]

In [29]:sorted(a.items(),key=operator.itemgetter(1))

Out[29]:[(2, 'a'), (1, 'b'), (3, 'c')]

或者不适用operator也行:

In [30]:sorted(a.items(),key=lambda x: x[1])

Out[30]:[(2, 'a'), (1, 'b'), (3, 'c')]



0 0
原创粉丝点击