(翻译)如何对python dict 类型按键(keys)或值(values)排序

如何对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

 

参见:

 

原文网址:http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/

 

posted @ 2015-06-22 21:15  klchang  阅读(1768)  评论(0编辑  收藏  举报