Sort Python dictionary

Tuesday, August 26th, 2008
Advertisement

Subscribe.
Enter your email:

Suppose that mydict is a dictionary defined by

mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4}

Remember that dictionary has no function sort, since it is unordered, not like a list, or tuple.

However, the key function, introduced in version 2.4, is helpful in sorting a dictionary.

To sort by items, and return the keys and items,

sorted( mydict.items(), key=lambda x: x[1] )

output:

[('b', 1), ('a', 2), ('d', 4), ('c', 5)]

To return only the keys, sorted by the items,

sorted( mydict.keys(), key=lambda x: mydict[x] )

output:

['b', 'a', 'd', 'c']

Note that, adding reverse=True at the end of the sorted function would produce a decending order list.

sorted( mydict.items(), key=lambda x: x[1] )

output:

[('c', 5), ('d', 4), ('a', 2), ('b', 1)]

Happy sorting.

If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>