Dictionary is an unordered data structure that contains key-value pairs similar to a map. It is a mutable data structure. And, it also allows for duplicate entries but only in values because the keys have to be distinct. In order to access a value, we take the help of keys as the index. Sometimes, when working with dictionaries cases may arise when we need to sort them. Therefore the question now arises as to how do I sort a dictionary by value?

Why do we sort a Dictionary ?

We need to sort a dictionary. Or for that matter any data structure because sorting helps to develop efficient analysis strategies. A sorted dictionary, therefore, yields a much better clarity and understanding in handling operations. It has an O(1) time complexity hence using dictionaries is a viable option whenever necessary.

Now, therefore, let’s get to the topic straightaway. And, see some examples along the way and also look at methods to sort a dictionary.

How do I sort a dictionary by value?

In this section, we will look at the various methods that we can utilize to sort a dictionary by value. This we will make clear by going through ample examples. So, let’s get a start rightaway.

Using sorted() method

The sorted() method is an in-built method in Python. It sorts the iterables in ascending or descending order. After sorting the weather it returns the sorted sequence, within the sort of a sorted list.

order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}
for a in sorted(order, key = order.get):
print(a, order[a])
How do I sort a dictionary by value?
# Output :
Pankaj 1
Kavin 2
Ayush 3
Shubham 4
Carl 5

Now, suppose we want to sort it in the descending order. Then, we will be using the statement, reverse = true, because, by default the order is ascending order. Let’s see the same in the subsequent code :

order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}

for a in sorted(order, key = order.get, reverse = True):
print(a, order[a])

# Output :
Carl 5
Shubham 4
Ayush 3
Kavin 2
Pankaj 1

Using the OrderedDict() Method

Dictionaries are generally without any order. Hence, it’s a very tedious or so to say near impossible to sort a dictionary directly. Therefore, we need to make use of the special OrderedDict subclass to do this task. Before, we proceed, it will be better to know in brief about OrderedDict. It is a subclass of dictionary. Also, it saves the order key-values as inserted while entering the pairs in the dictionary. It is a member of collections module.

Now, let us take an example to learn about this.

from collections import OrderedDict
order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}

x = OrderedDict(sorted(order.items(), key=lambda x: x[1]))
for key,value in x.items():
print(key, value)

# Output :
("Pankaj', 1)
('Kavin', 2)
('Ayush', 3)
('Shubham', 4)
('Carl', 5)


Note: This method is deprecated in newer version of Python. But, if you still use the older versions of Python, then this code will work for you absolutely fine.

Using Dictionary Comprehension

Using dictionary comprehension makes for comprehensive memory efficiency. As it is quite concise and gets executed in a single line of code. It has an expression component and a context component. The expression defines the ways we can map keys to values. The context loops over an iterable employing a single-line for loop. And it also defines which (key, value) pairs to incorporate within the new dictionary.

order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}

print({key : val for key, val in sorted(order.items(), key = lambda item : item[1])})

# Output :
{'Pankaj': 1, 'Kavin': 2, 'Ayush': 3, 'Shubham': 4, 'Carl': 5}

Here’s a reference for you on asking the user for input until a valid input is entered !!!

Using itemgetter() method together with sorted()

itemgetter() constructs a callable which accepts iterables and then displays the ‘nth’ element out of that. It is an in-buitl function in the Operator module.

from operator import itemgetter
order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}

for a in sorted(order.items(), key = itemgetter(1))
print(dict(a))      # this is done to ensure that the output is in dictionary form because itemgetter by default will give the output in the form of a tuple

# Output :
{'Pankaj': 1, 'Kavin': 2, 'Ayush': 3, 'Shubham': 4, 'Carl': 5}

Bonus Method : Make use of Counters

Counter is another subclass of dictionary which helps to count hashable items. We can use the Counter class to sort the integere values. Again, counter is a a part of the Collections module. The only pre-condition to use the counter is; the values in the key-value pairs shall be integers to make this work.

from collections import Counter
order = {
'Shubham': 4,
'Pankaj': 1,
'Ayush': 3,
'Kavin': 2,
'Carl': 5
}

count = dict(Counter(order).most_common())
print(count)

# Output :
{'Pankaj': 1, 'Kavin': 2, 'Ayush': 3, 'Shubham': 4, 'Carl': 5}

WRAPPING UP !!!

By and through this article I hope to have cleared your doubts and queries. In this tutorial we take a look at the various metods to sort any dictionary by value. The ample number of examples in this go a long way in making our task easier. Thus, making the concept and it’s utilization clearer in the long run. We have come to know about the sorted() method. Also, the itemgetter() method. Not to forget the counter subclass. The dictionary comprehension and similar other methods too.

If you have any further queries do write to us in the comment section for a prompt reply. Until next time, have a nice time and good bye !! See-ya !!! 🙂