w3resource

Python: Clear the list values within a given dictionary


A Python dictionary contains List as a value. Write a Python program to clear the list values in the said dictionary.

Visual Presentation:

Python Dictionary: Clear the list values within a given dictionary.

Sample Solution:

Python Code:

# Define a function 'test' that clears the list values within a dictionary.
def test(dictionary):
    # Iterate through the keys in the 'dictionary' and use the 'clear' method to empty the lists.
    for key in dictionary:
        dictionary[key].clear()
    return dictionary

# Create a dictionary 'dictionary' with keys as 'C1', 'C2', and 'C3', and lists as values.
dictionary = { 
    'C1': [10, 20, 30], 
    'C2': [20, 30, 40],
    'C3': [12, 34]
}

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

# Print a message indicating the intention to clear the list values in the dictionary.
print("\nClear the list values in the said dictionary:")

# Call the 'test' function to clear the list values within the dictionary and print the resulting dictionary.
print(test(dictionary)) 

Sample Output:

Original Dictionary:
{'C1': [10, 20, 30], 'C2': [20, 30, 40], 'C3': [12, 34]}

Clear the list values in the said dictionary:
{'C1': [], 'C2': [], 'C3': []}

Flowchart:

Flowchart: Clear the list values within a given dictionary.

Python Code Editor:

Previous: Write a Python program to convert string values of a given dictionary, into integer/float datatypes.
Next: A Python Dictionary contains List as value. Write a Python program to update the list values in the said dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.