Python - Dictionary values String Length Summation
Last Updated :
27 Apr, 2023
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 :
- We initialize a dictionary test_dict with three key-value pairs. The keys are strings and the values are also strings.
- We print the original dictionary using the print() function and str() to convert the dictionary to a string.
- We initialize a variable res to 0. This variable will store the sum of the lengths of all the string values in the dictionary.
- 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.
- 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))
OutputThe 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))
OutputThe 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.
Similar Reads
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Python - Add Dictionary Items
In Python, dictionaries are a built-in data structure that stores key-value pairs. Adding items to a dictionary is a common operation when you're working with dynamic data or building complex data structures. This article covers various methods for adding items to a dictionary in Python.Adding Items
3 min read
Python Add Dictionary Key
In Python, dictionaries are unordered collections of key-value pairs. Each item in a dictionary is accessed by its unique key, which allows for efficient storage and retrieval of data. While dictionaries are commonly used with existing keys, adding a new key is an essential operation when working wi
4 min read
Python Access Dictionary
In Python, dictionaries are powerful and flexible data structures used to store collections of data in key-value pairs. To get or "access" a value stored in a dictionary, we need to know the corresponding key. In this article, we will explore all the ways to access dictionary values, keys, and both
4 min read
Python Change Dictionary Item
A common task when working with dictionaries is updating or changing the values associated with specific keys. This article will explore various ways to change dictionary items in Python.1. Changing a Dictionary Value Using KeyIn Python, dictionaries allow us to modify the value of an existing key.
3 min read
Python Remove Dictionary Item
Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Letâs explore these methods.Using pop
2 min read
Get length of dictionary in Python
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods.Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in d
3 min read
Python - Value length dictionary
Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
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 whi
4 min read