# Python - Clearing list as dictionary value

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

In this article we consider a dictionary where the values are presented as lists. Then we consider clearing those values from the lists. We have two approaches here. One is to use the clear methods and another is to designate empty values to each key using list comprehension.

## Example

Live Demo

x1 = {"Apple" : [4,6,9,2],"Grape" : [7,8,2,1],"Orange" : [3,6,2,4]}
x2 = {"mango" : [4,6,9,2],"pineapple" : [7,8,2,1],"cherry" : [3,6,2,4]}
print("The given input is : " + str(x1))
# using loop + clear()
for k in x1:
x1[k].clear()
print("Clearing list as dictionary value is : " + str(x1))
print("\nThe given input is : " + str(x2))
# using dictionary comprehension
x2 = {k : [] for k in x2}
print("Clearing list as dictionary value is : " + str(x2))

## Output

Running the above code gives us the following result −

The given input is : {'Apple': [4, 6, 9, 2], 'Grape': [7, 8, 2, 1], 'Orange': [3, 6, 2, 4]}
Clearing list as dictionary value is : {'Apple': [], 'Grape': [], 'Orange': []}
The given input is : {'mango': [4, 6, 9, 2], 'pineapple': [7, 8, 2, 1], 'cherry': [3, 6, 2, 4]}
Clearing list as dictionary value is : {'mango': [], 'pineapple': [], 'cherry': []}