字典是无序的键值对,但有时候需要对其排序。

比较朴素的思路就是将字典转化为二元元组的列表,再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也有提及)

根据上面的内容,选取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 aux

D = dict(zip(range(100), range(100)))

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)")

结果:
1030003 function calls in 5.208 CPU seconds
30003 function calls in 0.400 CPU seconds
30003 function calls in 0.484 CPU seconds

使用lambda速度明显很慢,使用朴素的方法反而并不太差。