How to sort a dictionary by values in Python

By definition, dictionary are not sorted (to speed up access). Let us consider the following dictionary, which stores the age of several persons:

If you want to sort this dictionary by values (i.e., the age), you must be another data structure such as a list, or an ordered dictionary.

Use the sorted function and operator module

Sorted_d is a list of tuples sorted by the second element in each tuple. Each tuple contains the key and value for each item found in the dictionary. If you look at the content of this variable, you should get:

Use the sorted function and lambda function

If you do not want to use the operator module, you can use a lambda function:

The computation time is of the same order of magnitude as with the operator module. Would be interesting to test on large dictionaries.

Use the sorted function and return an ordered dictionary

In the previous methods, the returned objects are list of tuples. So we do not have a dictionary anymore. You can use an OrderedDict if you prefer:

Use sorted function and list comprehension

another method consists in using list comprehension and use the sorted function on the tuples made of (value, key).

Here the output is a list of tuples where each tuple contains the value and then the key:

Python 3.6 native sorting

In Python 3.6, the iteration through a dictionary is sorted. Consequently, you can just use:

The other advantage with this method is speed and the ability to return tuples as pairs of key/value or value/key.

Benchmark

Here is a quick benchmark made using the small dictionary from the above examples. Would be interesting to redo the test with a large dictionary. This was done within a PYthon 3.6 environment.

What you can see is that the native Python dictionary sorting is pretty cool followed by the combination of the lambda + list comprehension method. Overall using one of these four methods would be equivalent though (factor 2/3 at most).

This image was created with the following code.

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

Leave a Reply

Your email address will not be published.