Sort a Dictionary Without Using Sort Function in Python
Last Updated :
22 Feb, 2024
As we all know Dictionaries in Python are unordered by default, which means they can’t be sorted directly. However, we can sort the keys or values of a dictionary and create a new sorted dictionary from the sorted keys or values. We can sort a list in a Dictionary using the inbuilt dictionary sort() function. But in this article, we will learn how we can sort a Dictionary in a particular order without using the list sort() method.
Sorting a Dictionary Without Using Sort Function in Python
Below, are the methods of How to Sort a Dictionary in Python Without a Sort Function in Python:
- Using
min()
Function - Using the For loop
- Using
heapq
Module - Using Recursion
Sort a Dictionary in Python Using min
Function
In this approach, we repeatedly find and remove the key with the minimum value from the original dictionary, creating a sorted dictionary based on the values.
Python3
def sort_dict_min(original_dict):
sorted_dict = {}
while original_dict:
min_key = min(original_dict, key=original_dict.get)
sorted_dict[min_key] = original_dict.pop(min_key)
return sorted_dict
# Example Usage
original_dict = {'banana': 3, 'apple': 1, 'orange': 2}
print("Original Dictionary:", original_dict)
sorted_dict = sort_dict_min(original_dict)
print("Sorted Dictionary :", sorted_dict)
OutputOriginal Dictionary: {'banana': 3, 'apple': 1, 'orange': 2}
Sorted Dictionary : {'apple': 1, 'orange': 2, 'banana': 3}
Sort a Dictionary in Python Using Loop and sorted
Function
In this approach, we use a loop and the sorted()
function to iterate through the keys of the original dictionary in sorted order based on their values, creating a sorted dictionary.
Python3
def sort_dict_using_loop(original_dict):
sorted_dict = {}
for key in sorted(original_dict, key=original_dict.get):
sorted_dict[key] = original_dict[key]
return sorted_dict
# Example Usage
original_dict = {'banana': 3, 'apple': 1, 'orange': 2}
print("Original Dictionary:", original_dict)
sorted_dict = sort_dict_using_loop(original_dict)
print("Sorted Dictionary ", sorted_dict)
OutputOriginal Dictionary: {'banana': 3, 'apple': 1, 'orange': 2}
Sorted Dictionary {'apple': 1, 'orange': 2, 'banana': 3}
Sort a Dictionary in Python Using heapq
Module
In this approach, we use the heapq
module, this method finds the smallest items based on values, creating a sorted dictionary from the result.
Python3
import heapq
def sort_dict_heapq(original_dict):
sorted_items = heapq.nsmallest(len(original_dict),
original_dict.items(), key=lambda x: x[1])
sorted_dict = dict(sorted_items)
return sorted_dict
# Example Usage
original_dict = {'banana': 3, 'apple': 1, 'orange': 2}
print("Original Dictionary:", original_dict)
sorted_dict = sort_dict_heapq(original_dict)
print("Sorted Dictionary:", sorted_dict)
OutputOriginal Dictionary: {'banana': 3, 'apple': 1, 'orange': 2}
Sorted Dictionary: {'apple': 1, 'orange': 2, 'banana': 3}
Sort a Dictionary in Python Using Recursion
In this approach, we find and remove the key with the minimum value, creating a sorted dictionary by repeatedly updating it until the original dictionary is empty.
Python3
def sort_dict_recursive(original_dict):
if not original_dict:
return {}
min_key = min(original_dict, key=original_dict.get)
sorted_dict = {min_key: original_dict.pop(min_key)}
sorted_dict.update(sort_dict_recursive(original_dict))
return sorted_dict
# Example Usage
original_dict = {'banana': 3, 'apple': 1, 'orange': 2}
print("Original Dictionary:", original_dict)
sorted_dict = sort_dict_recursive(original_dict)
print("Sorted Dictionary :", sorted_dict)
OutputOriginal Dictionary: {'banana': 3, 'apple': 1, 'orange': 2}
Sorted Dictionary : {'apple': 1, 'orange': 2, 'banana': 3}
Conclusion
In this article, we studied on how to sort a dictionary in Python without using the built-in sorted function. From this article we understood it can be achieved through various approaches. The presented methods showcase different techniques, including using the min function, custom sorting functions, the heapq module, recursion, and a loop with the sorted function. Each method provides a unique way to create a sorted dictionary based on the values of the original dictionary.
Similar Reads
Python - Sorting a dictionary of tuples
This task becomes particularly useful when working with structured data, where tuples represent grouped information (e.g., names and scores, items and prices). Sorting such data enhances its readability and usability for further analysis. For example, consider a dictionary d = {'student3': ('bhanu',
3 min read
How to Sort a Dictionary by Value in Python
In Python, sorting a dictionary by its values is something that often comes up when we are working with the data for which there exists an ordered presentation or analysis. Python dictionaries do not have this value already ordered within it, but with a minute programming script sorting the dictiona
3 min read
Sorting Python Dictionary With Lists as Values
Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python. Sort a Dictionary with Lists as Values in Pyt
3 min read
How to Reverse a Dictionary in Python
Reversing a dictionary typically means swapping the keys and values, where the keys become the values and the values become the keys. In this article, we will explore how to reverse a dictionary in Python using a variety of methods. Using Dictionary ComprehensionDictionary comprehension is a concise
2 min read
Iterate Python Dictionary Using Enumerate() Function
Python dictionaries are versatile data structures used to store key-value pairs. When it comes to iterating through the elements of a dictionary, developers often turn to the enumerate() function for its simplicity and efficiency. In this article, we will explore how to iterate through Python dictio
3 min read
Python - Keys with shortest length lists in dictionary
Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1: Using len() +
4 min read
Python - Storing Elements Greater than K as Dictionary
Sometimes, while working with python lists, we can have a problem in which we need to extract elements greater than K. But sometimes, we don't require to store duplicacy and hence store by key value pair in dictionary. To track of number position of occurrence in dictionary. Method #1 : Using loop T
3 min read
Python | Find keys with duplicate values in dictionary
Given a dictionary, the task is to find keys with duplicate values. Let's discuss a few methods for the same. Method #1: Using Naive approach In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys C/C++ Code # Python code to demonstrate #
4 min read
Python - How to Sort a Dictionary by Kth Index Value
While working with Python, one might come to a problem in which one needs to perform a sort on a dictionary based on Kth index of value list. This can be typically in the case of scoring or web development. Letâs discuss a method by which this task can be performed. Input : test_dict = {'gfg' : [5,
6 min read
Sort a Nested Dictionary by Value in Python
Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read