Python - Clearing list as dictionary value

PythonServer Side ProgrammingProgramming

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': []}
raja
Published on 03-Mar-2020 06:24:53
Advertisements