How to sort Python dictionary

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']

Related

This entry was posted in Python and tagged , , , , . Bookmark the permalink.

2 Responses to How to sort Python dictionary

  1. Hanep says:

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

  2. Selinap says:

    Thanks for visiting. Adsense earning is very slow.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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