Python - Dictionary Values Mapped Summation
Last Updated :
22 Apr, 2023
- 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 mapped by 8 + 8 + 10 = 26. ( sum of list mapped ).
Input : test_dict = {4 : ['a', 'v', 'b', 'e'],
1 : ['g', 'f', 'g']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2}
Output : {4: 16, 1: 26}
Explanation : "g" has 8, "f" has 10 as magnitude, hence 1 is mapped by 8 + 8 + 10 = 26. ( sum of list mapped ).
Method 1 : Using loop + items()
In this, each key is iterated in the dictionary and each value of each dict. is iterated and summed using mapped sum dictionary initialized.
Python3
# Python3 code to demonstrate working of
# Dictionary Values Mapped Summation
# Using loop + items()
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
1 : ['g', 'f', 'g'],
3 : ['e', 'v']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values mapped
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
'b' : 4, 'e' : 7, 'v' : 2}
res = dict()
# items() getting keys and values
for key, vals in test_dict.items():
sum = 0
for val in vals:
# summing with mappings
sum += map_vals[val]
res[key] = sum
# printing result
print("The extracted values sum : " + str(res))
Output:
The original dictionary is : {4: ['a', 'v', 'b', 'e'], 1: ['g', 'f', 'g'], 3: ['e', 'v']}
The extracted values sum : {4: 16, 1: 26, 3: 9}
Time complexity: O(nm), where n is the number of keys in the dictionary and m is the average length of the value lists.
Auxiliary space: O(n), where n is the number of keys in the dictionary because we are creating a new dictionary to store the results.
Method #2 : Using dictionary comprehension + sum()
In this, we perform the task of getting sum of each value using sum(). The dictionary comprehension is used for getting keys and assigning to values sum corresponding in shorthand.
Python3
# Python3 code to demonstrate working of
# Dictionary Values Mapped Summation
# Using dictionary comprehension + sum()
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
1 : ['g', 'f', 'g'],
3 : ['e', 'v']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values mapped
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
'b' : 4, 'e' : 7, 'v' : 2}
# sum() gets sum of each mapped values
res = {key : sum(map_vals[val] for val in vals)
for key, vals in test_dict.items()}
# printing result
print("The extracted values sum : " + str(res))
Output:
The original dictionary is : {4: ['a', 'v', 'b', 'e'], 1: ['g', 'f', 'g'], 3: ['e', 'v']}
The extracted values sum : {4: 16, 1: 26, 3: 9}
Method #3: Using list comprehension + lambda function
- First, we initialize a dictionary called test_dict with some key-value pairs where each value is a list of characters.
We then print out the original dictionary using the print statement and the str() function to convert the dictionary to a string.
We initialize another dictionary called map_vals with some key-value pairs where each key is a character and each value is an integer.
We create a new dictionary called res by extracting the values from the original dictionary and applying the mappings from the map_vals dictionary.
Finally, we print out the result dictionary using the print statement and the str() function to convert the dictionary to a string.
Python3
# initializing dictionary
test_dict = {4 : ['a', 'v', 'b', 'e'],
1 : ['g', 'f', 'g'],
3 : ['e', 'v']}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values mapped
map_vals = {'a' : 3, 'g' : 8, 'f' : 10,
'b' : 4, 'e' : 7, 'v' : 2}
# extracting values and applying mappings
res = {key: sum(map(lambda val: map_vals[val], vals)) for key, vals in test_dict.items()}
# printing result
print("The extracted values sum : " + str(res))
OutputThe original dictionary is : {4: ['a', 'v', 'b', 'e'], 1: ['g', 'f', 'g'], 3: ['e', 'v']}
The extracted values sum : {4: 16, 1: 26, 3: 9}
Time complexity: O(n^2), where n is the number of elements in the original dictionary, due to the nested loops used to extract the values and apply the mappings.
Auxiliary space: O(n), where n is the number of elements in the original dictionary, due to the use of a dictionary to store the results.
Method 4 : using the reduce() function from the functools module.
Import the reduce function from the functools module.
Create a dictionary named test_dict with integer keys and list values.
Create a dictionary named map_vals with characters as keys and integer values.
Use the reduce() function with a lambda function to map and sum the values for each key in the test_dict dictionary.
The lambda function takes two arguments x and y. x is the accumulated sum and y is the current value in the list of values for each key in test_dict.
map_vals[y] maps each value in the list to its corresponding integer value in map_vals.
The reduce() function takes a third argument, which is the initial value of the accumulated sum. In this case, it is set to 0.
The result is a new dictionary named res, where each key is mapped to the sum of its corresponding values.
Finally, the program prints the resulting dictionary using the print() function.
Python3
# import required module
from functools import reduce
# initializing dictionary and map_vals
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}
# using reduce() to map and sum values for each key
res = {key: reduce(lambda x, y: x + map_vals[y], vals, 0) for key, vals in test_dict.items()}
# printing result
print("The extracted values sum : " + str(res))
OutputThe extracted values sum : {4: 16, 1: 26, 3: 9}
Time complexity of O(n*m). where n is the number of keys in the dictionary and m is the maximum number of values in the dictionary.
Auxiliary space complexity of O(n), where n is the number of keys in the dictionary and m is the maximum number of values in the dictionary.
Similar Reads
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 | 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 | 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
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 - 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 - 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 whi
4 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 tas
4 min read
Python - Mapping Key Values to Dictionary
We are given two list and we need to map key to values of another list so that it becomes dictionary. For example, we are given two list k = ['a', 'b', 'c'] and v = [1, 2, 3] we need to map the keys of list k to the values of list v so that the resultant output should be {'a': 1, 'b': 2, 'c': 3}.Usi
3 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
9 min read