What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Sort Dictionary by Value & Key in Python

  • Feb 15, 2021
  • 3 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
Sort Dictionary by Value & Key in Python

In this article, we will learn what is a dictionary and the need for sorting in the dictionary. Later, we will understand how we can sort the dictionary by value and by keys along with the example and corresponding output. So, let's get started!

What is Dictionary?

The dictionary is one of the data structures in the python language. Dictionary is an order collection of data items stored like a map, unlike any other data type. Dictionary stores the data in the form of key-value pair which provides more optimized data collection. Remember that the keys in the dictionary don't allow repetition. Therefore, dictionary items are ordered, changeable, and do not allow duplicates.

We can retrieve the data items in a dictionary using the corresponding key name. We can define the dictionary by a comma-separated list of key-value pairs between the curly braces({}).

Key and value inside the dictionary is separated by using a colon(:) between corresponding key and value. Remember that key must be a single element whereas value can be of any data type. 

Need for Sorting in Dictionary

The sorting of data is very important when we are dealing with a large amount of data. It is very difficult to get desired output quickly and efficiently when the data collection is very huge. In such cases, we can reduce the complexity of data collection by sorting it according to number series or alphabet series to get quick output.

For example, consider your phonebook in mobile, the contact details of the people are stored with the name as a key where no name should be repeated, and they are arranged in alphabetical order for effective searching techniques.

Therefore, when you want to search for the contact details of the person with a specific name, you jump to the initial of the name in your phonebook and reduce your time and effort by going through each contact detail in your phonebook. By this example, we can say that sorting of the dictionary is not only important for programming purposes but also highly important in our daily lives. 

Sort Dictionary By Value in Python

As we all know that dictionary contains key and value pairs and therefore, there is a total of 3 methods by which we can sort the dictionary using the value component. Let us understand those three methods in detail below:

1) Using for Loop

We can use the python sorted() method along with the for loop to sort the dictionary in python using value. In the method, we first create the list of the dictionary keys and sort the list of keys using the sorted() method along with them for a loop. The output will be the sorted dictionary as shown in the below example:

We can sort the dictionary in python with the help of the NumPy library. In the below example, we import the python library NumPy and sort the values of the dictionary using the 'argsort' method in the NumPy library. Later we create the list of dictionary keys using the list() method and sort the dictionary by combining it with the sorted() method to get the values of the dictionary. Lastly, we use for loop to get sorted dictionary as the output given below: 

Example

import numpy as np

dictionary = { 'A':1,'ABC':3,'ABCD':4,'AB':2 }
print("Dictionary: ", dictionary)
sorted_value_index = np.argsort(dictionary.values())
dictionary_keys = list(dictionary.keys())
sort_dictionary = {dictionary_keys[i]:sorted(dictionary.values())[i] for i in range(len(dictionary_keys))}
print("Sorted Dictionary by value: ", sort_dictionary)

 

Output

Dictionary:  {'A': 1, 'ABC': 3, 'ABCD': 4, 'AB': 2}
Sorted Dictionary by value:  {'A': 1, 'ABC': 2, 'ABCD': 3, 'AB': 4}

 

2) Using lambda Function

Python sorted() method along with lambda function can be used to sort a dictionary by value in python in a predefined order. Here, the python lambda function creates an anonymous function that helps to optimize the codes. The syntax of the lambda function will be as given below:

lambda arguments: expression

 
Example
 
dictionary = { 'A':1,'ABC':3,'ABCD':4,'AB':2 }
print("Dictionary: ", dictionary)
sort_dictionary= dict(sorted(dictionary.items(), key=lambda item: item[1])) 
print("Sorted Dictionary by value: ", sort_dictionary)
 
 
Output
 
Dictionary:  {'A': 1, 'ABC': 3, 'ABCD': 4, 'AB': 2}
Sorted Dictionary by value:  {'A': 1, 'AB': 2, 'ABC': 3, 'ABCD': 4}

 

3) Using dictionary.items() Method

In this method, we will use items() methods to sort the dictionary along with the sorted() method in python. The method will sort the dictionary by its values and return the sorted dictionary as shown below:

Example

from operator import itemgetter
dictionary = { 'A':1,'ABC':3,'ABCD':4,'AB':2 }
print("Dictionary: ", dictionary)
sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1))) 
print("Sorted Dictionary by value: ", sort_dict)

 

Output

Dictionary:  {'A': 1, 'ABC': 3, 'ABCD': 4, 'AB': 2}
Sorted Dictionary by value:  {'A': 1, 'AB': 2, 'ABC': 3, 'ABCD': 4}

 

Sort Dictionary by Key in Python

Apart from sorting the dictionary using values, we can also sort the dictionary using the keys component. Below are 3 methods to sort the dictionary using keys.

1) Using for Loop

We can sort the dictionary in python using keys with the help of the keys() method and for a loop. Here the keys are separated from the dictionary using the keys() method and then sorted with the help of for loop. As a result, we get the sorted dictionary as the output just like shown in the below example:

Example

dictionary = {'john':'1','alice':'90','rook':'45','emma':'22','roz':'11'} 
sorted_keys = sorted(dictionary.keys())
sorted_dict = {key:dictionary[key] for key in sorted_keys}
print(sorted_dict)

 

Output

{'alice': '90', 'emma': '22', 'john': '1', 'rook': '45', 'roz': '11'}

 

2) Using sorted() Method 

We can also sort the dictionary in python using the sorted() method. Here, we call the sorted method for the given dictionary and then sort it with the use of for loop for the given keys as shown in the example below:

Example

dictionary = {'john':'1','alice':'90','rook':'45','emma':'22','roz':'11'} 
dictionary1 = sorted(dictionary)
sorted_dict = {key:dictionary[key] for key in dictionary1}
print(sorted_dict) 

 

Output

{'alice': '90', 'emma': '22', 'john': '1', 'rook': '45', 'roz': '11'}
 

3) Using items() Method

We can sort the dictionary using keys with the help of the items() method. We call the dictionary for the sorted() method and then use the dictionary.items() to sort the dictionary by keys as shown in the below example:

Example

dictionary = {'john':'1','alice':'90','rook':'45','emma':'22','roz':'11'}
dictionary1 = sorted(dictionary.items())
print(dict(dictionary1))

 

Output

{'alice': '90', 'emma': '22', 'john': '1', 'rook': '45', 'roz': '11'}

 

Conclusion

Dictionary in python is generally used to store the large collection of ordered data and map them using key-value pairs. Sorting the dictionary in python helps to retrieve the desired output in an efficient manner and therefore, in the above article we have mentioned various methods to sort the dictionary in python by using dictionary keys as well as using dictionary values. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.