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
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
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
Python - Sort Dictionary key and values List Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read
Python - Sort Dictionary by key-value Summation Given a Dictionary, sort by summation of key and value. Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1} Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6} Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values. Input : test_dict = {3:5, 1:3, 4:6, 2:7} Output : {1: 3, 3: 5, 2: 7, 4:
5 min read