How-To
- How to sort a dict by keys (Python 2.4 or greater):
- mydict = {'carl':40,
- 'alan':2,
- 'bob':1,
- 'danny':3}
- for key in sorted(mydict.iterkeys()):
- print "%s: %s" % (key, mydict[key])
Taken from the Python FAQ: http://www.python.org/doc/faq/general/#why-doesn-t...t-sort-return-the-sorted-list. To sort the keys in reverse, add reverse=True as a keyword argument to the sorted function.
- How to sort a dict by keys (Python older than 2.4):
- keylist = mydict.keys()
- keylist.sort()
- for key in keylist:
- print "%s: %s" % (key, mydict[key])
- How to sort a dict by value (Python 2.4 or greater):
- for key, value in sorted(mydict.iteritems(), key=lambda (k,v): (v,k)):
- print "%s: %s" % (key, value)
Taken from Nick Galbreath's Digital Sanitation Engineering blog article.
- More Examples to sort dict by key/value
Related posts:
* Python data object motivated by desire for a mutab...namedtuple with default values — posted 2012-08-03
* How to sort a list of dicts in Python — posted 2010-04-02
* Python setdefault example — posted 2010-02-09
* How to conditionally replace items in a list — posted 2008-08-22
* How to use Python's enumerate and zip to iterate o...er two lists and their indices. — posted 2008-04-18
* How to invert a dict in Python — posted 2008-01-14
* Sort a Python dictionary by value
沒有留言:
張貼留言