Python字典如何排序啊,给例子谢谢
发布网友
发布时间:2022-04-06 09:52
我来回答
共2个回答
懂视网
时间:2022-04-06 14:13
热心网友
时间:2022-04-06 11:21
在Python2.7.x版本中, collections类增加了OrderedDict, 用法如下:
在Python2.7.x版本中, collections类增加了OrderedDict, 用法如下:
pywugw@pywugw-laptop:~$ /usr/local/bin/python2.7
Python 2.7b1 (r27b1:79927, Apr 26 2010, 11:44:19)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
#按key排序
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
#按value排序
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
#按key的长度排序
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])