How to sort Python dictionary

Tuesday, February 24th, 2009
Advertisement

Subscribe.
Enter your email:

To sort a Python dictionary, and append the keys into a list.

>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get)
['c', 'a', 'b']

To sort a Python dictionary, and append tuples of the key and value into a list.

>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]

To sort a Python dictionary, and append the keys into a tuple, and the values into a tuple.

>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> [(the_key, x[the_key]) for the_key in sorted(x, key=x.get)]
[('c', 1), ('a', 2), ('b', 3)]
>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> the_keys, the_vals = zip(*[(the_key, x[the_key]) \
for the_key in sorted(x, key=x.get)])
>>> the_keys
('c', 'a', 'b')
>>> the_vals
(1, 2, 3)

The results from the above examples are in ascending order. To sort in descending order, attach reverse=True at the end of the sorted() function.

>>> x = {'a': 2, 'c': 1, 'b': 3}
>>> sorted(x, key=x.get, reverse=True)
['b', 'a', 'c']
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

2 Responses to “How to sort Python dictionary”

  1. Hanep says:

    looking at the theme,.. , how was your adsense earning?

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>