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 dictionary of values.

Visual Presentation:

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

Sample Solution:

Python Code:

# Define a function 'test' that calculates the length of the values in a dictionary and returns a new dictionary with values as keys and their lengths as values.
def test(dictt):
    result = {}
    for val in dictt.values():
        # Calculate the length of each value and store it as a key-value pair in the 'result' dictionary.
        result[val] = len(val)
    return result

# Create a dictionary 'color_dict' with integer keys and color values.
color_dict = {1: 'red', 2: 'green', 3: 'black', 4: 'white', 5: 'black'}

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

# Print a message indicating the intention to calculate the length of dictionary values.
print("Length of dictionary values:")

# Call the 'test' function to calculate the length of values in the dictionary and print the result.
print(test(color_dict))

# Create a dictionary 'color_dict' with string keys and names as values.
color_dict = {'1': 'Austin Little', '2': 'Natasha Howard', '3': 'Alfred Mullins', '4': 'Jamie Rowe'}

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

# Print a message indicating the intention to calculate the length of dictionary values.
print("Length of dictionary values:")

# Call the 'test' function to calculate the length of values in the dictionary and print the result.
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}

Flowchart:

Flowchart: Find the length of a given dictionary values.

Python Code Editor:

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 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://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-53.php