Summary: In this programming example, we will learn different ways to sort a dictionary by key or value in Python.

The dictionary data structure in Python is equivalent to the Map data structure of C++ or Java.

It is an associative container (collection) that stores data values as key-value pairs.

Unlike sequences such as a list, which is indexed by a range of numbers, the dictionary is indexed by keys.

Before Python 3.6+, dictionary in Python was unordered. It means the dictionary does not used to preserve the sequence of data being inserted.

But the new dictionary implementation remembers the order of the items inserted, allowing us to arrange elements by key or value in Python.

Let us look at some ways how we can sort elements of the dictionary by key or value.

Sort Dictionary by Key

We can sort dictionary by key in two easy ways:

  • Using dict constructor with sorted() method.
  • By converting to a list of items.

Method 1: Using dict constructor with sorted() method

In this method, we transform the given dictionary into a list of tuples by using the .items() method, sort them using the sorted() method and finally convert the sorted result back to the Python dictionary using the dict constructor.

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

The sorted() method also accepts an optional boolean reverse argument. If we provide True as the value, it sorts the iterable object in descending order.

Method 2: By converting to a list of items

In this method, we don’t sort the dictionary in-place, but convert it into a list of items and sort them.

Similar to the previous method, we use the items() method to get the list of tuples and sort it using the sort() method of the 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 this method if the final result doesn’t have to be a dictionary object.

Sort Dictionary by Value

We can also sort the dictionary by values using the sorted() function. Let’s see two different approaches of doing so in Python.

Method 1: Using lambda function with sorted()

The sorted() method accepts an additional optional parameter i.e. key on the basis of which it sorts the elements.

In previous examples, we did not provide any value for it, so the sorted method by default selected the first element of tuples as key (which was used to be key in the dictionary) and sorted them on the basis of that.

If we change the value of key to lambda x: x[-1], the sorted method sorts list of tuples (dictionary converted using the .items() method) on the basis of the value.

x is the key-value pair and x[-1] is the second value of the tuple (which was used to be value in the dictionary).

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

asc_dict = dict(sorted(d.items(), key=lambda x: x[-1]))
print("Dictionary sorted in Ascending order by value", asc_dict)

desc_dict = dict(sorted(d.items(), key=lambda x: x[-1], reverse=True))
print("Dictionary sorted in Descending order by value", 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++'}

Overall in this method, we are instructing the sorted method to sort the dictionary by considering value as the key.

Method 2: Using itemgetter() with sorted()

In this method, we use the same approach as the previous method but instead of the lambda function use the itemgetter method of the operator module as the key parameter.

from operator import itemgetter

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

asc_dict = dict(sorted(d.items(), key=itemgetter(-1)))
print("Dictionary sorted in Ascending order by value", asc_dict)

desc_dict = dict(sorted(d.items(), key=itemgetter(-1), reverse=True))
print("Dictionary sorted in Descending order by value", 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++'}

The itemgetter(n) method constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the nth element out of it.

Leave a Reply

three × three =