Python | Summation of dictionary list values
Last Updated :
13 Apr, 2023
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.
Method #1: Using sum() + list comprehension
This task can be performed using sum function which can be used to get the summation and internal list comprehension can provide a mechanism to iterate this logic to all the keys of the dictionary.
Python3
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
res = sum ( len (sub) for sub in test_dict.values())
print ( "Summation of dictionary list values are : " + str (res))
|
Output
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
Time complexity: O(N), where N is the total number of elements in all the lists contained within the dictionary.
Auxiliary space: O(1), as it only uses a constant amount of auxiliary space to store the input dictionary and the result variable.
Method #2: Using sum() + map()
This task can also be performed using map function in place of list comprehension to extend the logic of finding the length, rest all the functionality remaining same as the above method.
Python3
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
res = sum ( map ( len , test_dict.values()))
print ( "Summation of dictionary list values are : " + str (res))
|
Output
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
Method #3: Using values(), extend() and len() methods
Python3
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
x = list (test_dict.values())
a = []
for i in x:
a.extend(i)
res = len (a)
print ( "Summation of dictionary list values are : " + str (res))
|
Output
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
Method #4: Using reduce()
Using reduce() and len(): This approach uses the reduce() function from the functools module to iteratively combine the values of the dictionary into a single iterable, and then uses the len() function to get the count of elements in the iterable. Time complexity is O(n) where n is the total number of elements in the lists, and auxiliary space is O(n) where n is the total number of elements in the lists.
Python3
from functools import reduce
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
res = len ( reduce ( lambda x, y: x + y, test_dict.values()))
print ( "Summation of dictionary list values are : " + str (res))
|
Output
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
The time complexity of this code is O(N*M), 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(M), where M is the length of the longest list in the dictionary.
Method#5 Using Numpy library
Python3
import numpy as np
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
values_array = np.array( list (test_dict.values()))
values_array = values_array.flatten()
result = np. sum (values_array)
print ( len (result))
|
Output:
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
Time complexity: O(n)
Auxiliary Space: O(n)
Method#6: Using a for loop:
- The function is defined with a single parameter called test_dict, which represents the dictionary that will be input to the function.
- A variable called result is initialized to 0. This variable will be used to keep track of the sum of the lengths of all the sub-lists in the dictionary.
- The function uses a for loop to iterate through all the values of the input dictionary. The values() method of a dictionary returns a view object that contains the values of the dictionary.
- For each sub-list in the dictionary, the length of the sub-list is calculated using the len() function, and the result is added to the result variable.
- Once all the sub-lists have been processed, the final value of result is returned from the function.
- Finally, the function is tested with a sample dictionary called test_dict, and the result is printed to the console using the print() function.
Python3
def sum_dict_values(test_dict):
result = 0
for sub_list in test_dict.values():
result + = len (sub_list)
return result
test_dict = { 'gfg' : [ 5 , 6 , 7 ], 'is' : [ 10 , 11 ], 'best' : [ 19 , 31 , 22 ]}
print ( "The original dictionary is : " + str (test_dict))
result = sum_dict_values(test_dict)
print ( "Summation of dictionary list values are : " + str (result))
|
Output
The original dictionary is : {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
Summation of dictionary list values are : 8
Time complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Python - List of dictionaries all values Summation
Given a list of dictionaries, extract all the values summation. Input : test_list = [{"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2}] Output : 12 Explanation : 2 + 2 +...(6-times) = 12, sum of all values. Input : test_list = [{"Apple" : 3, "Mango" : 2, "Grapes" : 2
5 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 | 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 - 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 - Add Values to Dictionary of List
A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Letâs look at some commonly used methods to efficien
3 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 - 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 | Summation of tuples in list
Sometimes, while working with records, we can have a problem in which we need to find the cumulative sum of all the values that are present in tuples. This can have applications in cases in which we deal with a lot of record data. Let's discuss certain ways in which this problem can be solved. Metho
7 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 Convert Dictionary to List of Values
Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read