
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Clearing list as dictionary value
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
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': []}
- Related Articles
- Clearing a Dictionary using Javascript
- Dictionary with index as value in Python
- Get dictionary keys as a list in Python
- Python – Convert List to Index and Value dictionary
- Python – Replace value by Kth index value in Dictionary List
- Python – Sort Dictionary List by Key’s ith Index value
- Python program to Convert Matrix to Dictionary Value List
- Python – Extract Key’s Value, if Key Present in List and Dictionary
- Python – Inverse Dictionary Values List
- Python – Create dictionary from the list
- Count number of items in a dictionary value that is a list in Python
- List vs tuple vs dictionary in Python
- Dictionary creation using list contents in Python
- Converting list string to dictionary in Python
- Python – All combinations of a Dictionary List

Advertisements