最近突然想到以前有在網路看到Dict做排序
覺得這些以後還用的到
所以記錄一下…
1 2 3 4 5 6 #http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/ for key in sorted(mydict.iterkeys()): print "%s: %s" % (key, mydict[key]) for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)): print "%s: %s" % (key, value) 寫成現有method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #http://code.activestate.com/recipes/52306-to-sort-a-dictionary/ # (IMHO) the simplest approach: def sortedDictValues1(adict): items = adict.items() items.sort() return [value for key, value in items] # an alternative implementation, which # happens to run a bit faster for large # dictionaries on my machine: def sortedDictValues2(adict): keys = adict.