Given dictionary, sort its items using key-value difference.
Input : test_dict = {3 : 9, 1 : 4, 9 : 13, 1 : 10, 8 : 9 }
Output : {8: 9, 9: 13, 3: 9, 1: 10}
Explanation : 1 < 4 < 6 < 9, is increasing difference.
Input : test_dict = {3 : 9, 1 : 4, 9 : 13, 1 : 9, 8 : 9 }
Output : {8: 9, 9: 13, 3: 9, 1: 9}
Explanation : 1 < 4 < 6 < 8, is increasing difference.
Method #1 : Using abs() + sort() + dictionary comprehension
In this, task of sorting is done using sort(), items() is used to get key-value pairs of dictionary as tuple list. Then, abs() is used to compute absolute difference and passed as key to sort. At last, dictionary comprehension is used to reconvert result to dictionary.
# Python3 code to demonstrate working of
# Sort by dictionary key-value difference
# Using abs() + sort() + dictionary comprehension
# getting abs diff
def abs_diff(ele):
return abs(ele[0] - ele[1])
# initializing dictionary
test_dict = {3 : 9, 1 : 4, 9 : 13, 1 : 10, 8 : 9 }
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting using sort
test_dict_list = list(test_dict.items())
test_dict_list.sort(key = abs_diff)
# reordering to dictionary
res = {ele[0] : ele[1] for ele in test_dict_list}
# printing result
print("The sorted dictionary : " + str(res))
Method #2 : Using sorted() + lambda + abs() + dictionary comprehension
In this, we perform task of sorting and using sorted() and lambda function is used to input logic of getting absolute difference using abs().
# Python3 code to demonstrate working of
# Sort by dictionary key-value difference
# Using sorted() + lambda + abs() + dictionary comprehension
# initializing dictionary
test_dict = {3 : 9, 1 : 4, 9 : 13, 1 : 10, 8 : 9 }
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting using sorted()
# lambda function to render logic
test_dict_list = sorted(list(test_dict.items()), key = lambda ele : abs(ele[0] - ele[1]))
# reordering to dictionary
res = {ele[0] : ele[1] for ele in test_dict_list}
# printing result
print("The sorted dictionary : " + str(res))