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
Delete items from dictionary while iterating in Python
A Python dictionary is a collection which is unordered, changeable and indexed. They have keys and values and each item is referenced using the key. Modifying a dictionary while iterating over it can cause runtime errors, so we need special techniques to safely delete items during iteration.
Using del with Collected Keys
In this approach we first collect the keys that need to be deleted, then iterate through this separate list to delete the items. This prevents modification of the dictionary during iteration ?
Example
# Given dictionary
days_dict = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
# Get keys with value in 2,3
to_del = [key for key in days_dict if key in (2, 3)]
# Delete keys
for key in to_del:
del days_dict[key]
# New Dictionary
print(days_dict)
{1: 'Mon', 4: 'Thu', 5: 'Fri'}
Using list() to Create Key Copy
We can create a list containing the keys from the dictionary and iterate over this copy while modifying the original dictionary. This approach allows us to use conditional expressions during iteration ?
Example
# Given dictionary
days_dict = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
# Get keys with even value
for key in list(days_dict):
if (key % 2) == 0:
del days_dict[key]
# New Dictionary
print(days_dict)
{1: 'Mon', 3: 'Wed', 5: 'Fri'}
Using items() to Delete by Values
Instead of keys we can also use the items of the dictionary to select entries for deletion based on their values. We collect the keys of items that match our criteria, then delete them ?
Example
# Given dictionary
days_dict = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
keys_to_delete = []
# Get keys with specific values
for key, val in days_dict.items():
if val in ('Tue', 'Fri'):
keys_to_delete.append(key)
for key in keys_to_delete:
del days_dict[key]
# New Dictionary
print(days_dict)
{1: 'Mon', 3: 'Wed', 4: 'Thu'}
Using Dictionary Comprehension
A more Pythonic approach is to create a new dictionary with only the items you want to keep, rather than deleting items from the existing dictionary ?
Example
# Given dictionary
days_dict = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'}
# Keep only odd keys
filtered_dict = {k: v for k, v in days_dict.items() if k % 2 != 0}
print(filtered_dict)
{1: 'Mon', 3: 'Wed', 5: 'Fri'}
Comparison of Methods
| Method | Memory Usage | Best For |
|---|---|---|
| Collected Keys | Creates temporary list | Complex conditions |
| list(dict) | Creates key copy | Simple iteration |
| Dictionary Comprehension | Creates new dict | Functional approach |
Conclusion
Never modify a dictionary while iterating directly over it. Use list(dict) for simple cases or dictionary comprehension for a more Pythonic approach. Always create a separate collection of keys to delete when using complex conditions.
