Open In App

Python – Sort Dictionary by Values Summation

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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’: 8} 
Explanation : Sorted by sum, and replaced.

Method #1 : Using sorted() + dictionary comprehension + sum()

The combination of above functions can be used to solve this problem. In this, we first sum all the list elements using sum() and then next step is to perform sorting of all the keys according to sum extracted using sorted().

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using dictionary comprehension + sum() + sorted()
 
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# summing all the values using sum()
temp1 = {val: sum(int(idx) for idx in key)
           for val, key in test_dict.items()}
 
# using sorted to perform sorting as required
temp2 = sorted(temp1.items(), key = lambda ele : temp1[ele[0]])
 
# rearrange into dictionary
res = {key: val for key, val in temp2}
         
# printing result
print("The sorted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
The sorted dictionary : {'is': 9, 'Gfg': 17, 'best': 18}

Time complexity: O(n log n), where n is the number of key-value pairs in the dictionary. The sorted() function has a time complexity of O(n log n) due to the sorting operation, and the dictionary comprehension to compute the sum of values has a time complexity of O(n).
Auxiliary Space: O(n), where n is the number of key-value pairs in the dictionary. The program creates two new dictionaries (temp1 and res), both of which have a space complexity of O(n), and the sorted() function also requires additional space for the sorting operation.

Method #2 : Using map() + dictionary comprehension + sorted() + sum()

The combination of above functions can be used to solve this problem. In this, we perform the task of mapping the logic of summation using map().

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using map() + dictionary comprehension + sorted() + sum()
 
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# summing all the values using sum()
# map() is used to extend summation to sorted()
temp = {key: sum(map(lambda ele: ele, test_dict[key])) for key in test_dict}
res = {key: temp[key] for key in sorted(temp, key = temp.get)}       
 
# printing result
print("The sorted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
The sorted dictionary : {'is': 9, 'Gfg': 17, 'best': 18}

The time complexity of this code is O(NMlogN), where N is the number of keys in the dictionary and M is the length of the longest list in the dictionary. 

The space complexity of this code is O(N), where N is the number of keys in the dictionary. 

Method #3: Using defaultdict() from the collections module

  • Create an empty defaultdict with an initial value of 0.
  • Loop through each key-value pair in the dictionary and add up the values for each key using the sum() function. Store the summed values in the defaultdict with the corresponding keys.
  • Sort the defaultdict by value using the sorted() function and a lambda function that returns the value for each key-value pair in the dictionary.
  • Create a new dictionary from the sorted key-value pairs.
  • Print the result.

Python3




from collections import defaultdict
 
# initializing dictionary
test_dict = {'Gfg' : [6, 7, 4], 'is' : [4, 3, 2], 'best' : [7, 6, 5]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using defaultdict() to sum the values
temp_dict = defaultdict(int)
for key, val in test_dict.items():
    temp_dict[key] = sum(val)
 
# sorting the dictionary based on the summed values
sorted_dict = dict(sorted(temp_dict.items(), key=lambda x: x[1]))
 
# printing result
print("The sorted dictionary : " + str(sorted_dict))


Output

The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
The sorted dictionary : {'is': 9, 'Gfg': 17, 'best': 18}

Time complexity: O(n log n), where n is the number of key-value pairs in the dictionary
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.



Similar Reads

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 certain ways in which this task can be performed. M
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 tuple() + sum() + zip() + values() The combinatio
4 min read
Python - Dictionary values String Length Summation
Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using s
4 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 can be performed. Method #1 : Using loop + items(
8 min read
Python - Product and Inter Summation dictionary values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform product of entire value list and perform summation of product of each list with other. This kind of application in web development and day-day programming. Lets discuss certain ways in which this task can be performed. Input : test_dict = {'gfg' : [
4 min read
Python - Dictionary Keys whose Values summation equals K
Given a dictionary and a value K, extract keys whose summation of values equals K. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 17 Output : ['Best', 'for'] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 19 Output : ['Best', 'Geeks'] Explana
9 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 : "g" has 8, "f" has 10 as magnitude, hence 1 is mapp
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: 6} Explanation : 4 < 8 < 9 < 10 are incr
5 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 task can be performed. Method #1: Using sum() + list
6 min read
Python - Summation Grouping in Dictionary List
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to perform the grouping of dictionaries according to specific key, and perform summation of certain keys while grouping similar key's value. This is s peculiar problem but can have applications in domains such as web development. Let's discuss a certain way in
5 min read
Practice Tags :
three90RightbarBannerImg