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: 40
Taken from Nick Galbreath's Digital Sanitation Engineering blog article


See also:

2 comments:

Marius said...

Thank you.

Sven Siegmund said...

Thanks a lot. Exactly what I was looking for.

About

This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

http://www.saltycrane.com/blog/.

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.