mydict = {‘carl‘:40, ‘alan‘:2, ‘bob‘:1, ‘danny‘:3} for key in sorted(mydict.iterkeys()): print "%s: %s" % (key, mydict[key])
结果:
alan: 2 bob: 1 carl: 40 danny: 3
摘自 Python FAQ: http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list.
若按相反的顺序,按键(keys)排序,则需在sorted函数中添加 reverse=True 参数。
keylist = mydict.keys() keylist.sort() for key in keylist: print "%s: %s" % (key, mydict[key])
这段程序结果与上面的结果相同。
for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)): print "%s: %s" % (key, value)
结果:
bob: 1 alan: 2 danny: 3 carl: 40
摘自 Nick Galbreath‘s Digital Sanitation Engineering blog article
参见:
sorted
in 2.1 Built-in Functions and the .sort()
method in 3.6.4 Mutable Sequence Typesin the Python Library Reference.
原文网址:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
(翻译)如何对python dict 类型按键(keys)或值(values)排序
原文:http://www.cnblogs.com/klchang/p/4593897.html