Open In App

Python – Dictionary values String Length Summation

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

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 sum() + generator expression + len() The combination of above functions can be used to perform this task. In this, we compute length using len(), summation using sum() and iteration using generator expression. 

Python3




# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using sum() + len() + generator expression
from collections import ChainMap
 
# initializing dictionary
test_dict = {'gfg' : '2345',
             'is' : 'abcde',
             'best' : 'qwerty'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Dictionary values String Length Summation
# Using sum() + len() + generator expression
res = sum((len(val) for val in test_dict.values()))
     
# printing result
print("The string values length summation : " + str(res))


Output : 

The original dictionary is : {‘is’: ‘abcde’, ‘best’: ‘qwerty’, ‘gfg’: ‘2345’} The string values length summation : 15

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), as the program does not use any additional data structure whose space requirements depend on the size of the input.

Method #2 : Using map() + len() + sum() This performs the task similar to above function. The only difference is that iteration is performed using map() than generator expression. 

Python3




# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using map() + len() + sum()
 
# initializing dictionary
test_dict = {'gfg' : '2345',
             'is' : 'abcde',
             'best' : 'qwerty'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Dictionary values String Length Summation
# Using map() + len() + sum()
res = sum(map(len, test_dict.values()))
     
# printing result
print("The string values length summation : " + str(res))


Output : 

The original dictionary is : {‘is’: ‘abcde’, ‘best’: ‘qwerty’, ‘gfg’: ‘2345’} The string values length summation : 15

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required

Method 3 : using a for loop:

step-by-step approach :

  1. We initialize a dictionary test_dict with three key-value pairs. The keys are strings and the values are also strings.
  2. We print the original dictionary using the print() function and str() to convert the dictionary to a string.
  3. We initialize a variable res to 0. This variable will store the sum of the lengths of all the string values in the dictionary.
  4. We use a for loop to iterate over all the values in the dictionary. For each value, we compute its length using the len() function and add it to the res variable.
  5. After the loop completes, we print the result using the print() function and str() to convert the integer res to a string.

Python3




# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using for loop
 
# initializing dictionary
test_dict = {'gfg' : '2345',
             'is' : 'abcde',
             'best' : 'qwerty'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Dictionary values String Length Summation
# Using for loop
res = 0
for val in test_dict.values():
    res += len(val)
     
# printing result
print("The string values length summation : " + str(res))


Output

The original dictionary is : {'gfg': '2345', 'is': 'abcde', 'best': 'qwerty'}
The string values length summation : 15

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(1), as we are only using a constant amount of extra space to store the res variable.

Method #4: Using reduce() from functools module

Step-by-Step Approach:

  • Import the reduce() function from the functools module.
  • Initialize the dictionary test_dict.
  • Print the original dictionary.
  • Use the reduce() function along with a lambda function to iterate through the values of the dictionary and add up the lengths of the values.
  • Print the result.

Python3




# Python3 code to demonstrate working of
# Dictionary values String Length Summation
# Using reduce()
 
# initializing dictionary
test_dict = {'gfg' : '2345',
             'is' : 'abcde',
             'best' : 'qwerty'}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Dictionary values String Length Summation
# Using reduce()
from functools import reduce
res = reduce(lambda x, y: x + len(y), test_dict.values(), 0)
 
# printing result
print("The string values length summation : " + str(res))


Output

The original dictionary is : {'gfg': '2345', 'is': 'abcde', 'best': 'qwerty'}
The string values length summation : 15

Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary space: O(1) as we are not using any extra space.



Previous Article
Next Article

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 - 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 - 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': 8} Explanation : Sorted by sum, and replaced. Meth
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 | 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
Python - Tuple to Dictionary Summation conversion
Sometimes, while working with Python tuples, we can have a problem in which we can have data points in tuples, and we need to convert them to dictionary after performing summation of similar keys. This kind of operation can also be extended to max, min or product. This can occur in data domains. Let's discuss certain ways in which this task can be
5 min read
Practice Tags :