Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Clearing list as dictionary value
In Python, you may have a dictionary where values are lists and need to clear all the list values while keeping the keys. There are two main approaches: using the clear() method to empty existing lists in-place, or using dictionary comprehension to assign new empty lists.
Using Loop with clear() Method
The clear() method empties existing lists in-place, preserving the original list objects ?
fruits = {"Apple": [4, 6, 9, 2], "Grape": [7, 8, 2, 1], "Orange": [3, 6, 2, 4]}
print("Original dictionary:", fruits)
# Clear each list in-place
for key in fruits:
fruits[key].clear()
print("After clearing:", fruits)
Original dictionary: {'Apple': [4, 6, 9, 2], 'Grape': [7, 8, 2, 1], 'Orange': [3, 6, 2, 4]}
After clearing: {'Apple': [], 'Grape': [], 'Orange': []}
Using Dictionary Comprehension
Dictionary comprehension creates a new dictionary with empty lists assigned to each key ?
fruits = {"mango": [4, 6, 9, 2], "pineapple": [7, 8, 2, 1], "cherry": [3, 6, 2, 4]}
print("Original dictionary:", fruits)
# Create new dictionary with empty lists
fruits = {key: [] for key in fruits}
print("After clearing:", fruits)
Original dictionary: {'mango': [4, 6, 9, 2], 'pineapple': [7, 8, 2, 1], 'cherry': [3, 6, 2, 4]}
After clearing: {'mango': [], 'pineapple': [], 'cherry': []}
Comparison
| Method | Modifies Original | Memory Usage | Best For |
|---|---|---|---|
clear() |
Yes (in-place) | Lower | When other references to lists exist |
| Dictionary Comprehension | No (creates new) | Higher | When you want a fresh dictionary |
Conclusion
Use clear() for in-place modification when memory efficiency matters. Use dictionary comprehension when you need a completely new dictionary with empty lists.
Advertisements
