字典是無序的鍵值對,但有時候須要對其排序。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