w3resource

Python: Clear the list values within a given dictionary

Python dictionary: Exercise-50 with Solution

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

Sample Solution:

Python Code:

def test(dictionary):
    for key in dictionary:
        dictionary[key].clear()
    return dictionary

dictionary = { 
               'C1' : [10,20,30], 
               'C2' : [20,30,40],
               'C3' : [12,34]
             }
print("\nOriginal Dictionary:")
print(dictionary)
print("\nClear the list values in the said 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': []}

Pictorial Presentation:

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

Flowchart:

Flowchart: Clear the list values within a given dictionary.

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 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 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()