In this tutorial, we look at various methods to sort the dictionary by value in Python. We will understand why it is required and how to do so.
Table of Contents – Python sort dictionary by value
- Why do we need to sort the Python dictionary?
- Various methods to sort dictionary by value in Python
- By converting data in the dictionary to list
- Using Bubble Sort
- Using sorted() Method
- Using itemgetter() Method
- Using dict.items() and sorted() Functions
- By performing operations directly on the dictionary
- Using for Loop
- Using the sorted() Function
- Using a Lambda Function
- Using dictionary.items() Method
- Closing thoughts
Why do we need to sort the Python dictionary by value?
In Python, the dictionary stores unordered data that contains “key:value” pairs seperated by commas inside curly brackets. The Python dictionary class does not allow to sort to sort the items in its object. We can retrieve the values when the key exists and is known.
Consider a huge amount of data in a Python dictionary. In this case, to reduce the complexity of data collection by sorting the data will lead to a quick output. Thus, to save time and increase efficiency over large data, like a phonebook, we need to sort the Python dictionary.
We can sort the dictionary using list and performing sorting over the list. Let us see the various ways to do this.
Various methods to sort dictionary by value in Python
By converting data in the dictionary to list
We will first look at way to convert the data in dictionary to a list. We then perform sorting over the list to sort the Python dictionary.
Example-
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=list(markdict.items())
print(marklist)
Output-
[('Tom', 67), ('Tina', 54), ('Akbar', 87), ('Kane', 43), ('Divya', 73)]
Here, we are converting the dictionary to a list using the list() function. Once the list is ready, we can perform operations over it to get desired results on the dictionary.
Using Bubble Sort
Example –
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
l=len(marklist)
for i in range(l-1):
for j in range(i+1,l):
if marklist[i][1]>marklist[j][1]:
t=marklist[i]
marklist[i]=marklist[j]
marklist[j]=t
sortdict=dict(marklist)print(sortdict)
Output-
{'Kane': 43, 'Tina': 54, 'Tom': 67, 'Divya': 73, 'Akbar': 87}
In this example, we use simple Bubble sort using a temporary variable t and sorting the values in the list.
Using sorted() Method
The sorted() function in Python returns a sorted list from the specified iterables and returns a list of sorted items.
Syntax-
sorted (iterable, key, reverse)
Example-
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
Here, in the sorted() function, the iterable is markdict.items and the key is set as lambda x:x[1]. After sorting the items, we create a new dictionary sortdict to call the sorted data.
Using itemgetter() Method
In Python, the itemgetter() function returns a callable object from its operand. Using the itemgetter() function with the sorted() function will return sorted items in the dictionary by value.
Example-
import operator
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist= sorted(markdict.items(), key=operator.itemgetter(1))
sortdict=dict(marklist)
print(sortdict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
The operator.itemgetter(item) function returns a callable object that fetches item from its operand using the operand’s __getitem() method.
Using dict.items() and sorted() Functions
The dict.items() method and the sorted() function can be used together to return the list of items sorted by values in a dictionary.
Example-
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=sorted((value, key) for (key,value) in markdict.items())
sortdict=dict([(k,v) for v,k in marklist])
print(sortdict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
In the above example, we sort the dictionary using sorted() function and create a new dictionary sortdict with the sorted values.
By performing operations directly on the dictionary
The Python dictionary can also be sorted without converting the items to list. Here are the ways to do it.
Using for Loop
By using a for loop along with sorted() function in Python, we can sort the dictionary by value. Here is an example for the same.
Example-
dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
sorted_values = sorted(dict1.values()) # Sort the values
sorted_dict = {}
for i in sorted_values:
for k in dict1.keys():
if dict1[k] == i:
sorted_dict[k] = dict1[k]
break
print(sorted_dict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
Here, we first use the sort() function to order the values of dictionary. The sorted() function does not re-order the dictionary in-place, hence, we store it’s value in sorted_values. We then then loop through the sorted values, finding the keys for each value. This is finally added to the new dictionary sorted_dict[k].
Using the sorted() Function
Example-
dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
sorted_dict = {}
sorted_keys = sorted(dict1, key=dict1.get)
for w in sorted_keys:
sorted_dict[w] = dict1[w]
print(sorted_dict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
In this example, we use the function key on each element before comparing the values for sorting. Another function used here is get() to return the values corresponding to the dictionary’s key. Thus, the function sorted(dict1, key=dict1.get) returns the list of keys with sorted values.
Using a Lambda Function
We can use Python function sorted() with lambda function to sort a dictionary by value. The syntax of lambda function is as follows.
Syntax-
lambda arguments: expression
Example-
dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
sorted_tuples = sorted(dict1.items(), key=lambda item: item[1])
sorted_dict = {k: v for k, v in sorted_tuples}
print(sorted_dict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
Using dictionary.items() Method
The items() method can sort the dictionary by values and return the sorted values. Below is the example of how we can use this method.
Example-
from operator import itemgetter
dictionary = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1)))
print(sort_dict)
Output-
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
In this example, we use the functions sorted(), set the iterable as dictionary.items() and the key as key=itemgetter(1) to get the sorted values of the dictionary.
Closing thoughts
We can sort the Python dictionary by values in two ways. One is by converting dictionary data to list and then sorting the list. The other way is to sort the dictionary directly.