w3resource

Python: Find the length of a given dictionary values

Python dictionary: Exercise-53 with Solution

Write a Python program to find the length of a given dictionary values.

Sample Solution:

Python Code:

def test(dictt):
    result = {}
    for val in dictt.values(): 
        result[val] = len(val) 
    return result    

color_dict = {1 : 'red', 2 : 'green', 3 : 'black', 4 : 'white', 5 : 'black'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Length of dictionary values:")
print(test(color_dict))

color_dict = {'1' : 'Austin Little', '2' : 'Natasha Howard', '3' : 'Alfred Mullins', '4' : 'Jamie Rowe'}
print("\nOriginal Dictionary:")
print(color_dict)
print("Length of dictionary values:")
print(test(color_dict))

Sample Output:

Original Dictionary:
{1: 'red', 2: 'green', 3: 'black', 4: 'white', 5: 'black'}
Length of dictionary values:
{'red': 3, 'green': 5, 'black': 5, 'white': 5}

Original Dictionary:
{'1': 'Austin Little', '2': 'Natasha Howard', '3': 'Alfred Mullins', '4': 'Jamie Rowe'}
Length of dictionary values:
{'Austin Little': 13, 'Natasha Howard': 14, 'Alfred Mullins': 14, 'Jamie Rowe': 10}

Pictorial Presentation:

Python Dictionary: Find the length of a given dictionary values.

Flowchart:

Flowchart: Find the length of a given dictionary values.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract a list of values from a given list of dictionaries.
Next: Write a Python program to get the depth of a dictionary.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Free up Memory:

  • Manual garbage collection can be performed on timely or event based mechanism.
import gc
collected_objects = gc.collect()