How to sort a Python dict (dictionary) by keys or values
This is my OLD blog. I've copied this post over to my NEW blog at:
http://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/
You should be redirected in 2 seconds.
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])Results:
alan: 2 bob: 1 carl: 40 danny: 3
Taken from the Python FAQ: http://www.python.org/doc/faq/general/#why-doesn-t-list-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)Results:
bob: 1 alan: 2 danny: 3 carl: 40Taken from Nick Galbreath's Digital Sanitation Engineering blog article
See also:
- The documentation for
sorted
in 2.1 Built-in Functions and the.sort()
method in 3.6.4 Mutable Sequence Types in the Python Library Reference.
2 comments:
Thank you.
Thanks a lot. Exactly what I was looking for.
Post a Comment