w3resource

Python: Total length of all values of a given dictionary with string values

Python dictionary: Exercise-65 with Solution

Write a Python program to get the total length of all values in a given dictionary with string values.

Visual Presentation:

Python Dictionary: Total length of all values of a given dictionary with string values.

Sample Solution:

Python Code:

# Define a function 'test' that takes a dictionary 'dictt' as an argument.
def test(dictt):
    # Use a generator expression to calculate the sum of lengths of all values in the input dictionary.
    result = sum((len(values) for values in dictt.values()))
    return result

# Create a dictionary 'color' with color codes as keys and color names as values.
color = {'#FF0000':'Red', '#800000':'Maroon', '#FFFF00':'Yellow', '#808000':'Olive'}

# Print a message indicating the start of the code section and display the original dictionary.
print("\nOriginal dictionary:")
print(color)

# Print a message indicating the purpose and demonstrate the 'test' function's usage
# to calculate the total length of all string values in the dictionary.
print("\nTotal length of all values of the said dictionary with string values:")
print(test(color)) 

Sample Output:

Original dictionary:
{'#FF0000': 'Red', '#800000': 'Maroon', '#FFFF00': 'Yellow', '#808000': 'Olive'}

Total length of all values of the said dictionary with string values:
20

Flowchart:

Flowchart: Total length of all values of a given dictionary with string values.

Python Code Editor:

Previous: Write a Python program to create a key-value list pairings in a given dictionary.
Next: Write a Python program to check if a specific Key and a value exist in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-65.php