如何对dict类型按键(keys)排序(Python 2.4 或更高版本):
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 参数。
如何对dict类型按键(keys)排序(比Python 2.4 更旧版本):
keylist = mydict.keys() keylist.sort() for key in keylist: print "%s: %s" % (key, mydict[key])
这段程序结果与上面的结果相同。
如何对dict类型按值(values)排序(Python 2.4 或更高版本):
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
参见:
- The documentation for
sorted
in 2.1 Built-in Functions and the.sort()
method in 3.6.4 Mutable Sequence Typesin the Python Library Reference. - Sorting Dictionaries by Value in Python (improved?) by Gregg Lind August 30, 2008
原文网址:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
时间: 2024-11-06 22:44:22