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 Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Python: Tips of the Day

Invokes the provided function after ms milliseconds:

Example:

from time import sleep

def tips_delay(fn, ms, *args):
  sleep(ms / 1000)
  return fn(*args)
print(tips_delay(
  lambda x: print(x),
  1000,
  'w3r'
))

Output:

w3r
None