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.

d = {2: 'Python',  1: 'Java', 3: 'C++'}

asc_dict = dict(sorted(d.items()))
desc_dict = dict(sorted(d.items(), reverse=True))

print("Dictionary sorted in Ascending order by key")
print(asc_dict)

print("Dictionary sorted in Descending order by key")
print(desc_dict)

output

Dictionary sorted in Ascending order by key
{1: 'Java', 2: 'Python', 3: 'C++'}
Dictionary sorted in Descending order by key
{3: 'C++', 2: 'Python', 1: 'Java'}

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.

d = { 2 : 'Python',  1 : 'Java', 3 : 'C++'}

#converting dictionary to list of dict_items
l = list(d.items())

#sorting and displaying dict_items in ascending order
l.sort()
print("Dictionary sorted in Ascending order by key")
print(l)

#sorting and displaying dict_items in descending order
l.sort(reverse=True)
print("Dictionary sorted in Descending order by key")
print(l)

output

Dictionary sorted in Ascending order by key                                                          
[(1, 'Java'), (2, 'Python'), (3, 'C++')]                                                             
Dictionary sorted in Descending order by key                                                         
[(3, 'C++'), (2, 'Python'), (1, 'Java')]

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.

d = {2: 'Python',  1: 'Java', 3: 'C++'}

asc_dict = dict(sorted(d.items(), key=lambda x: x[-1]))
desc_dict = dict(sorted(d.items(), key=lambda x: x[-1], reverse=True))

print("Dictionary sorted in Ascending order by value")
print(asc_dict)

print("Dictionary sorted in Descending order by value")
print(desc_dict)

output

Dictionary sorted in Ascending order by value
{3: 'C++', 1: 'Java', 2: 'Python'}
Dictionary sorted in Descending order by value
{2: 'Python', 1: 'Java', 3: 'C++'}

Method 2:

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

import operator

d = {2: 'Python',  1: 'Java', 3: 'C++'}

asc_dict = dict(sorted(d.items(), key=operator.itemgetter(-1)))
desc_dict = dict(sorted(d.items(), key=operator.itemgetter(-1), reverse=True))

print("Dictionary sorted in Ascending order by value")
print(asc_dict)

print("Dictionary sorted in Descending order by value")
print(desc_dict)

output

Dictionary sorted in Ascending order by value
{3: 'C++', 1: 'Java', 2: 'Python'}
Dictionary sorted in Descending order by value
{2: 'Python', 1: 'Java', 3: 'C++'}

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

18 + two =