In this post, we will discuss how can we sort a dictionary in python either by key or by value.

Recommended: Dictionary in Python

Sort Dictionary by Key

Method 1:

We can sort a dictionary with respect to its key by using sorted() function of python. By default it sorts the dictionary in ascending order, to sort in descending order we have to assign revrese=True in the function parameter.

output

Method 2:

In this method, we will first convert the dictionary into a list of dictinary items using items() method and list() constructor. After that we will sort it using sort() method of list object.

output

Use the above method when it is not necessary for the final result to be in the dictionary format.

Sort Dictionary by Key

Method 1:

We can easily sort the dictionary by its values using sorted() function.

Only extra we need to add is the key=lambda x: x[-1] in the sorted funtion parameter.

x is the key-value pair and x[-1] is the value (-1 in python reference the last part of any data structure).

Overall the key statement basically instructs the sorted function to sort a dictionary by considering value as key.

output

Method 2:

In this method, we will use the operator module of python instead of the lambda function for the key parameter.

output

operator is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n) constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.

If you have any doubts or suggestions then please comment below.

Leave a Reply