字典是无序的键值对,但有时候须要对其排序。python
比较朴素的思路就是将字典转化为二元元组的列表,再sort。
根据此博文http://www.kunli.info/2009/05/07/sorting-dictionaries-by-value-in-python/的介绍,最好的排序方法是PEP265http://www.python.org/dev/peps/pep-0265/ (python cookbook 5.4也有说起)ide
根据上面的内容,选取3种方法作测试。代码以下:
from profile import run
from operator import itemgetter
def sbv1(d, reverse=False):
"""using a lambda to get the key"""
return sorted(d.iteritems(), key=lambda x:x[1], reverse=reverse)测试
def sbv2(d, reverse=False):
"""PEP265"""
return sorted(d.iteritems(), key=itemgetter(1), reverse=reverse)排序
def sbv3(d, reverse=False):
"""python cookbook 5.4"""
aux = [(d[k], k) for k in d]
aux.sort()
if reverse:
aux.reverse()
return auxip
D = dict(zip(range(100), range(100)))get
run("for ii in xrange(10000): sbv1(D, reverse=True)")
run("for ii in xrange(10000): sbv2(D, reverse=True)")
run("for ii in xrange(10000): sbv3(D, reverse=True)")it
结果:
1030003 function calls in 5.208 CPU seconds
30003 function calls in 0.400 CPU seconds
30003 function calls in 0.484 CPU secondsio
使用lambda速度明显很慢,使用朴素的方法反而并不太差。function