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
# Python3 code to demonstrate working of
# Summation of dictionary list values
# using sum() + list comprehension
# initialize dictionary
test_dict = {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Summation of dictionary list values
# using sum() + list comprehension
res = sum(len(sub) for sub in test_dict.values())
# printing result
print("Summation of dictionary list values are : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Summation of dictionary list values
# using sum() + map()
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Summation of dictionary list values
# using sum() + map()
res = sum(map(len, test_dict.values()))
# printing result
print("Summation of dictionary list values are : " + str(res))
OutputThe 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
# Python3 code to demonstrate working of
# Summation of dictionary list values
# initialize dictionary
test_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Summation of dictionary list values
x=list(test_dict.values())
a=[]
for i in x:
a.extend(i)
res=len(a)
# printing result
print("Summation of dictionary list values are : " + str(res))
OutputThe 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
# initialize dictionary
test_dict = {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Summation of dictionary list values
# Using reduce() and len()
# reduce() method applies a given function to all elements in an iterable and returns a single value
# len() method returns the length of the passed iterable
res = len(reduce(lambda x, y: x + y, test_dict.values()))
# printing result
print("Summation of dictionary list values are : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
OutputThe 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
# initialize dictionary
test_dict = {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# convert dictionary values to numpy array
values_array = np.array(list(test_dict.values()))
# flatten array to 1D
values_array = values_array.flatten()
# sum the values in the array
result = np.sum(values_array)
print(len(result))
#This code is contributed by Vinay Pinjala.
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):
# Initialize a variable to store the result
result = 0
# Iterate through all the values of the dictionary
for sub_list in test_dict.values():
# Add the length of each sub-list to the result
result += len(sub_list)
# Return the result
return result
# Test the function with a sample dictionary
test_dict = {'gfg': [5, 6, 7], 'is': [10, 11], 'best': [19, 31, 22]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
result = sum_dict_values(test_dict)
print("Summation of dictionary list values are : " + str(result))
#This is code is contributed by Jyothi pinjala
OutputThe 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 Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read