Python - Sort Dictionary by Value Difference
Last Updated :
25 Apr, 2023
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 problem can come in data domain. Let's discuss a way in which this problem can be solved.
Method : Using sorted() + lambda + abs() + dictionary comprehension
The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(), lambda function is used to provide the logic and abs() function is used to compute the absolute difference.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by Value Difference
# Using sorted() + lambda + abs() + dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : [34, 87],
'is' : [10, 13],
'best' : [19, 27],
'for' : [10, 50],
'geeks' : [15, 45]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary by Value Difference
# Using sorted() + lambda + abs() + dictionary comprehension
res = dict(sorted(test_dict.items(), key = lambda sub: abs(sub[1][0] - sub[1][1])))
# printing result
print("The sorted dictionary : " + str(res))
Output :
The original dictionary is : {'gfg': [34, 87], 'is': [10, 13], 'best': [19, 27], 'for': [10, 50], 'geeks': [15, 45]} The sorted dictionary : {'is': [10, 13], 'best': [19, 27], 'geeks': [15, 45], 'for': [10, 50], 'gfg': [34, 87]}
Time Complexity: O(nlogn), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method 2 : using the items() method
Explanation:
We define the sort_by_difference function that takes an item (key-value pair) of the dictionary and returns the absolute difference between the two values in the list.
We use the sorted function with the key parameter set to the sort_by_difference function to sort the dictionary items based on the value difference.
We convert the sorted items back to a dictionary using the dict constructor and assign it to the res variable.
We print the sorted dictionary using the print function.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by Value Difference
# Using items() method and custom function for sorting
# initializing dictionary
test_dict = {'gfg' : [34, 87],
'is' : [10, 13],
'best' : [19, 27],
'for' : [10, 50],
'geeks' : [15, 45]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# custom function for sorting
def sort_by_difference(item):
key, value = item
return abs(value[0] - value[1])
# Sort Dictionary by Value Difference
# Using items() method and custom function for sorting
res = dict(sorted(test_dict.items(), key=sort_by_difference))
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary is : {'gfg': [34, 87], 'is': [10, 13], 'best': [19, 27], 'for': [10, 50], 'geeks': [15, 45]}
The sorted dictionary : {'is': [10, 13], 'best': [19, 27], 'geeks': [15, 45], 'for': [10, 50], 'gfg': [34, 87]}
The time complexity of the sorting algorithm used in the sorted function is O(n log n) in the worst case, where n is the number of items in the dictionary.
The auxiliary space used in this approach is O(n), where n is the number of items in the dictionary.
Similar Reads
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 List by Dictionary values Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
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 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 by value list length While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
4 min read