Sort a Dictionary in Python

Filed Under: Python
Sorting Dictionary In Python (1)

Introduction

In this tutorial, we are going to take a look at the various ways following which we can Sort a Dictionary in Python.

In Python, a Dictionary is a collection of key-value pairs. The sequence of such key and value pairs is separated by commas. These pairs are called items.

Different Ways to sort a Dictionary in Python

As mentioned above, a dictionary item consists of a key and its corresponding value. Hence, sorting for a dictionary can be performed by using any one of the key or value parts as a parameter.

So, let us now take a look at the different methods by which we can sort a dictionary by key or by value.

1. Sort Dictionary by Key

We can directly sort a dictionary using the built-in sorted() method in Python. This can be done by passing the dictionary itself and a function that specifies the parameter on the basis of which the sorting is to be done(in this case key).

Let us see how.

d = { 5: 1 , 4: 2 , 3: 3 , 2: 4 , 1: 5 }

print("The original dictionary: ", d)

#sorting by key
a = dict(sorted(d.items(), key=lambda x: x[0]))

print("After sorting by key: ", a)

Output:

The original dictionary:  {5: 1, 4: 2, 3: 3, 2: 4, 1: 5}
After sorting by key:  {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}

Here,

  • The d.items() method returns a list of tuples(items) containing the keys and their corresponding values,
  • The lambda function returns the key(0th element) for a specific item tuple,
  • When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary.

Remember, this method can be used in Python 3.6+ versions as it considers dictionaries as ordered sequences. For older versions, we can replace the lambda function with the itemgetter() method from the operator module. Let us see how.

from operator import itemgetter

d = { 5: 1 , 4: 2 , 3: 3 , 2: 4 , 1: 5 }
print("Original Dict: ", d)

#sorting by key
s_d = dict(sorted(d.items(), key=itemgetter(0)))
print("Sorted dict: ", s_d)

Output:

Original Dict:  {5: 1, 4: 2, 3: 3, 2: 4, 1: 5}
Sorted dict:  {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}

Here also the methods sorted() and items() work the same way. But in place of a lambda function, the itemgetter(0) method returns a callable object that fetches the 0th item from its operand using the operand’s __getitem__() method. In this case, as we need to sort by key, we consider the 0th element.

2. Sort a Dictionary by Value

Sorting a dictionary by value is similar to sorting by key. The only difference being that this type the parameter on the basis of which the sorting would be done is the value part of the corresponding items.

Hence as we did earlier, we can use the sorted() method along with a lambda function for Python 3.6+ versions. Let us see how.

d = { 0: 'd', 1: 'c', 2: 'b', 3: 'a' }

print("The original dictionary: ", d)

#sorting by value
a = dict(sorted(d.items(), key=lambda x: x[1]) )

print("After sorting by value: ", a)

Output:

The original dictionary:  {0: 'd', 1: 'c', 2: 'b', 3: 'a'}
After sorting by value:  {3: 'a', 2: 'b', 1: 'c', 0: 'd'}

Similarly here, according to the values returned by the lambda function(x[1] value for an item x) the dictionary d is sorted.

Again for older versions of Python follow the below-mentioned method.

from operator import itemgetter

d = { 0: 'd', 1: 'c', 2: 'b' , 3: 'a' }
print("Original Dict: ", d)

#sorting by value
s_d = dict(sorted(d.items(), key=itemgetter(1)))
print("Sorted dict: ", s_d)

Output:

Original Dict:  {0: 'd', 1: 'c', 2: 'b', 3: 'a'}
Sorted dict:  {3: 'a', 2: 'b', 1: 'c', 0: 'd'}

Similarly, sorted() along with d.items() and itemgetter(1) methods sort the dictionary d on the basis of value.

3. Sorting in reverse order

The sorted() method comes with another argument reverse. That can be used for specifying the order in which the sorting is to be done. If passed True, the sorting takes place in reverse order(descending). And if False is passed(default), the sorting takes place in ascending order.

Let us try to understand this by an example where we try to reverse sort a dictionary by key.

d = { 'a': 23, 'g': 67, 'e': 12, 45: 90}

print("The original dictionary: ", d)

#sorting by value in reverse
a = dict(sorted(d.items(), reverse = True, key=lambda x: x[1]))
print("After sorting by value in reverse order: ", a)

#sorting by value in ascending order
a = dict(sorted(d.items(), key=lambda x: x[1]))#by default reverse is set to False
print("After sorting by value in ascending order: ", a)

Output:

The original dictionary:  {'a': 23, 'g': 67, 'e': 12, 45: 90}
After sorting by value in reverse order:  {45: 90, 'g': 67, 'a': 23, 'e': 12}
After sorting by value in ascending order:  {'e': 12, 'a': 23, 'g': 67, 45: 90}

From the above output, it is clear that passing the reverse parameter as True the above dictionary is sorted in reverse order(descending).

Conclusion

So in this tutorial, we learned how we can sort a dictionary in Python using various methods.

For any further questions, feel free to use the comments below.

References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages