Python - Sort Dictionary by key-value Summation
Last Updated :
18 May, 2023
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: 6}
Explanation : 4 < 8 < 9 < 10 are increasing summation of keys and values.
Method 1: Using sorted() + lambda + items()
In this sort operation is performed using sorted(), lambda function is used to provide additional logic. The items() is used to get both keys and values.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by key-value Summation
# Using sorted() + lambda + items()
# initializing dictionary
test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorted() to sort, lambda provides key-value addition
res = sorted(test_dict.items(), key=lambda sub: sub[0] + sub[1])
# converting to dictionary
res = {sub[0]: sub[1] for sub in res}
# printing result
print("The sorted result : " + str(res))
Output:
The original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Time Complexity: O(n*nlogn), where n is the length of the list test_dict
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 dictionary comprehension and sorted() function
Use dictionary comprehension to create a new dictionary with sorted key-value pairs. Sort the dictionary items using the lambda function which returns the sum of key-value pairs. Finally, use sorted() method to sort the dictionary items based on the lambda function result.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by key-value Summation
# Using dictionary comprehension and sorted()
# initializing dictionary
test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# sorting dictionary by key-value summation
res = {k: v for k, v in sorted(test_dict.items(), key=lambda x: x[0]+x[1])}
# printing result
print("The sorted result : " + str(res))
OutputThe original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Time complexity: O(n log n), where n is the number of items in the dictionary. This is because sorting the dictionary items takes O(n log n) time complexity.
Auxiliary space: O(n), where n is the number of items in the dictionary. This is because we create a new dictionary with the same number of items as the original dictionary.
Method 3: Using the sum of its keys and values (Naive Approach)
- Initialize the dictionary.
- Create a list of tuples containing (key+value, key, value) instead of (key, value) pairs.
- Sort the list based on the first element of the tuple (i.e. the sum of the key and value) using the sorted() function.
- Create a new dictionary by iterating through the sorted list of tuples and adding each (key, value) pair to a new dictionary.
Python3
# Initialize dictionary
test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
# create list of tuples with (key+value, key, value)
tuple_list = [(k+v, k, v) for k, v in test_dict.items()]
# sort list based on the first element of the tuple
sorted_list = sorted(tuple_list)
# Creating new dictionary from sorted list of tuples
res = {}
for tup in sorted_list:
res[tup[1]] = tup[2]
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Printing sorted dictionary
print("The sorted result : " + str(res))
OutputThe original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Time complexity: O(n logn)
Method 4: Using list comprehension + for loop
Approach:
- Initialize the dictionary test_dict.
- Print the original dictionary.
- Create a list list of tuples (key, value, key+value) using a list comprehension.
- Sort the list lst by key+value summation using the sorted() function and a lambda function that returns the third element of each tuple.
- Create a new dictionary res from the sorted list using dictionary comprehension.
- Print the sorted dictionary.
Python3
# Python3 code to demonstrate working of
# Sort Dictionary by key-value Summation
# Using for loop and list comprehension
# Initializing dictionary
test_dict = {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Creating a list of tuples (key, value, key+value)
lst = [(k, v, k+v) for k, v in test_dict.items()]
# Sorting the list by key+value summation
lst = sorted(lst, key=lambda x: x[2])
# Creating a new dictionary from the sorted list
res = {k: v for k, v, _ in lst}
# Printing resultant answer
print("The sorted result : " + str(res))
OutputThe original dictionary is : {3: 5, 1: 3, 4: 6, 2: 7, 8: 1}
The sorted result : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6}
Time complexity: O(n log n) due to the use of the sorted() function.
Auxiliary space: O(n) for the list.
Similar Reads
Python - Sort Dictionary by Values Summation
Give a dictionary with value lists, sort the keys by summation of values in value list. Input : test_dict = {'Gfg' : [6, 7, 4], 'best' : [7, 6, 5]} Output : {'Gfg': 17, 'best': 18} Explanation : Sorted by sum, and replaced. Input : test_dict = {'Gfg' : [8], 'best' : [5]} Output : {'best': 5, 'Gfg':
4 min read
Python | Value summation of key in dictionary
Many operations such as grouping and conversions are possible using Python dictionaries. But sometimes, we can also have a problem in which we need to perform the aggregation of values of key in dictionary list. This task is common in day-day programming. Let's discuss certain ways in which this tas
6 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 - Nested Dictionary values summation
Sometimes, while working with Python dictionaries, we can have problem in which we have nested records and we need cumulative summation of it's keys values. This can have possible application in domains such as web development and competitive programming. Lets discuss certain ways in which this task
8 min read
Python - Dictionary Values Mapped Summation
Given a dictionary with a values list, our task is to extract the sum of values, found using mappings. Input : test_dict = {4 : ['a', 'v', 'b', 'e'], 1 : ['g', 'f', 'g'], 3 : ['e', 'v']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2} Output : {4: 16, 1: 26, 3: 9} Explanation : "
6 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
Python | Summation of dictionary list values
Sometimes, while working with Python dictionaries, we can have its values as lists. In this can, we can have a problem in that we just require the count of elements in those lists as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let's discuss c
6 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 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