當前位置:成語大全網 - 新華字典 - Python字典如何排序啊,給例子謝謝

Python字典如何排序啊,給例子謝謝

在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)])