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:

You should be redirected in 2 seconds.

How to sort a dict by keys (Python 2.4 or greater):
mydict = {'carl':40,

for key in sorted(mydict.iterkeys()):
    print "%s: %s" % (key, mydict[key])
alan: 2
bob: 1
carl: 40
danny: 3

Taken from the Python FAQ:

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()
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)
bob: 1
alan: 2
danny: 3
carl: 40
Taken from Nick Galbreath's Digital Sanitation Engineering blog article

See also:


Marius said...

Thank you.

Sven Siegmund said...

Thanks a lot. Exactly what I was looking for.


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

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.