Python - Sort dictionary by Tuple Key Product
Last Updated :
28 Apr, 2023
Given dictionary with tuple keys, sort dictionary items by tuple product of keys.
Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Explanation : 6 < 18 < 32 < 40, key products hence retains order.
Input : test_dict = {(20, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12}
Output : {(6, 3) : 9, (8, 4): 10, (10, 4): 12, (20, 3) : 3, }
Explanation : 18 < 32 < 40 < 60, key products hence adjusts order.
Method #1 : Using dictionary comprehension + lambda + sorted()
This is one of the ways in which this task can be performed. In this, we perform sort() using sorted() and lambda function is used to compute product over which sort can be performed.
Python3
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dictionary comprehension + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dictionary comprehension reassigs dictionary by order
res = {key: test_dict[key] for key in sorted(test_dict.keys(), key = lambda ele: ele[1] * ele[0])}
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}
Method #2 : Using dict() + sorted() + lambda
The combination of above functions can be used to solve this problem. In this, similar method is used as above method. The only difference being items arrangement done using dict() rather than dictionary comprehension after computing keys ordering .
Python3
# Python3 code to demonstrate working of
# Sort dictionary by Tuple Key Product
# Using dict() + sorted() + lambda
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() over lambda computed product
# dict() used instead of dictionary comprehension for rearrangement
res = dict(sorted(test_dict.items(), key = lambda ele: ele[0][1] * ele[0][0]))
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (6, 4): 12, (5, 6): 3, (8, 4): 10}
Method #3: Using itemgetter function from the operator module
Step by Step Algorithm
- Import itemgetter module from operator
- Initialize the test_dict
- Sort the dictionary based on the product of keys using itemgetter
- Reassign the sorted dictionary back to the original dictionary
- Print the sorted dictionary
Python3
from operator import itemgetter
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting the dictionary based on product of keys using itemgetter
res = dict(sorted(test_dict.items(), key=itemgetter(0), reverse=False))
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (5, 6): 3, (6, 4): 12, (8, 4): 10}
Complexity Analysis :
Time complexity: O(nlogn) where n is the number of items in the dictionary. The time complexity is mainly due to the sorting operation.
Space complexity: O(n), where n is the number of items in the dictionary. The space complexity is mainly due to the storage of the sorted dictionary.
Method #4: Using the heapq module's heapify() and heappop() functions
- Import the heapq module to use its functions for sorting.
- Initialize the dictionary to be sorted.
- Print the original dictionary.
- Convert the dictionary to a list of tuples, with the key product as the first element of each tuple.
- Use heapq.heapify() to sort the list of tuples in place based on the first element of each tuple (i.e., the key product).
- Create a new dictionary from the sorted list of tuples, with the first element (i.e., the tuple key) as the key of each dictionary element and the second element (i.e., the dictionary value) as the value of each dictionary element.
- Print the sorted dictionary.
Python3
import heapq
# initializing dictionary
test_dict = {(5, 6) : 3, (2, 3) : 9, (8, 4): 10, (6, 4): 12}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# convert dictionary to list of tuples and heapify
temp_list = [(k, v) for k, v in test_dict.items()]
heapq.heapify(temp_list)
# create new dictionary from sorted list
res = dict(heapq.heappop(temp_list) for i in range(len(temp_list)))
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary is : {(5, 6): 3, (2, 3): 9, (8, 4): 10, (6, 4): 12}
The sorted dictionary : {(2, 3): 9, (5, 6): 3, (6, 4): 12, (8, 4): 10}
The time complexity of this implementation is O(nlogn) because of the sorting operation
The space complexity is also O(n) because we are creating a new dictionary of the same size as 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
Python | Sort nested dictionary by key
Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
4 min read
Python program to sort Dictionary by Key Lengths
Given Dictionary, sort by its key lengths. Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3} Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3} Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order. Input : test_dict = {"Gfg" : 4, "for" : 3, "ge
4 min read
Python | Sort dictionary keys to list
Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python - Tuple value product in dictionary
Sometimes, while working with data, we can have a problem in which we need to find the product of tuple elements that are received as values of dictionary. We may have a problem to get index wise product. Letâs discuss certain ways in which this particular problem can be solved. Method #1 : Using tu
5 min read
Sort Python Dictionary by Value
Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
3 min read
Python - Sort Dictionary by Values and Keys
Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
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
Python - Sort Dictionary by Value Difference
Sometimes, while working with Python dictionaries, we can have problem in which in which we need to perform sorting of items on basis of various factors. One such can be on basis of absolute difference of dual value list. This can occur in Python > 3.6, as dictionaries are ordered. This kind of p
3 min read