Javaexercise.com

How To Sort A Python Dictionary By Value

Dictionary is a data structure in python that stores its values in the form of key-value pairs. Sorting a dictionary by values is a tough but possible task.

In this article, we are going to learn how to sort a dictionary by values.

Python provides us with a method called sorted(). There are several ways to sort a dictionary by values using the sorted() method.

Another way to sort a dictionary by values is by using the collections module.

Let's understand with some running examples.

Sorted() Method in Python

The sorted() method is used to sort any iterable object in python. It sorts the iterable object and returns a new object with the sorted values. The syntax of this method is:

sorted(object, key, reverse)

This method takes three arguments: object, key, reverse.

  • object: This is the object that needs to be sorted. This is the only required argument.

  • key: This is the function that allows us to do custom sorting. This is an optional argument.

  • reverse: This argument is set to true, sorts the object in descending order. By default, it is set to false.

Note: The sorting takes place by the key argument. Let us now look at examples of sorting a dictionary by values using the sorted() method.

Sorting dictionary by value in Python

In this example, we pass the dictionary.get() method as the key argument. This enables us to use the values as keys, according to which object will be sorted. One issue with this method is that it breaks the key-value relationship. The object returned after the sorted() function call is a list of keys sorted by the values. This will become more clear after the following example:

letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
​
sorted_letter = sorted(letter_frequency, key= letter_frequency.get)
​
print(sorted_letter)

Output:

['f', 'b', 'z', 'a']

As you can see from the above output, the letters are sorted in ascending order according to the values.

But we have lost our key-value relationship, to get that relationship we will need to refer back to our original dictionary. We passed the reverse argument as true to get results in descending order. See the code below:

letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
​
sorted_letter = sorted(letter_frequency, key= letter_frequency.get , reverse= True)
​
for s in sorted_letter:
    print(s , letter_frequency[s])

Output:

a 98
z 87
b 45
f 12

Sorting Dictionary By Reversing the Key-Value Relationship in Python

We can store the key-value pairs as value-keys pairs and store them in a temporary list. We can then call the sorted() function on that list, this will sort the data by keys without disturbing or ruining the relationship between the pairs. Look at the example below:

letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
​
temp_list = []
​
for (k ,v) in letter_frequency.items():
    temp_tuple = (v , k)
    temp_list.append(temp_tuple)
​
sorted_letter = sorted(temp_list, reverse= True)
​
print(sorted_letter)

Output:

a 98
z 87
b 45
f 12

The dictionary.items() method returns a view object, containing the key-value pairs as tuples in a list. We can also convert the returned sorted list into a dictionary. See the code below.

sorted_letter = dict(sorted(temp_list, reverse= True))
​
print(sorted_letter)

Output:

{98: 'a', 87: 'z', 45: 'b', 12: 'f'}

An important point to note here is that after python 3.7 the order of the dictionary remains intact. If you are using any version below 3.7 then would have to use OrderedDict.

Sort Dictionary Using zip() function in Python

This code example of sorting is just the previous, but instead of using a loop to convert key-values pairs to value-keys pairs, we will use the zip() method. Look at the example below:

letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
​
sorted_letter = sorted(zip(letter_frequency.values(), letter_frequency.key()), reverse= True)
​
print(sorted_letter)

Output:

[(98, 'a'), (87, 'z'), (45, 'b'), (12, 'f')]

The zip() method maps the values to keys. Like the previous method, we can convert it into a dictionary.

Sorting Dictionary Using Lambda function in Python

We can pass a lambda function to the key argument to sort a dictionary. In this lambda function, we will return the value field of tuple inside the list returned by the items() method. This method has an advantage over the other methods, as it does not disturb the key-value relationship. The key-value pairs are not changed to value-keys pairs.

letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
​
sorted_letter = dict(sorted(letter_frequency.items(),
                        key = lambda x : x[1],
                        reverse= True))
​
print(sorted_letter)

Output:

{'a': 98, 'z': 87, 'b': 45, 'f': 12}

 

Sorting Dictionary by Using Collection Module in Python

The collection module has a class called Counter. The Counter class takes tuple, list, or dictionary as input and holds the frequency of each element in the object.

The Counter class has a method called most_common() which returns a list containing the elements sorted by values in descending order.

The returned list can then be converted into a dictionary to get a sorted dictionary. See the example below:

from collections import Counter
letter_frequency = {'f': 12 , 'a' : 98 , 'b' : 45 , 'z' : 87}
counter = Counter(letter_frequency)
sorted_letter = dict(counter.most_common())
print(sorted_letter)

Output:

{'a': 98, 'z': 87, 'b': 45, 'f': 12}

 

Conclusion

In this article, we saw two major methods: sorted and most_common, to sort a dictionary by values. We then saw several ways to use the sorted() method to achieve our goal.