How to Delete Items from a Dictionary While Iterating Over It in Python?

Estimated read time 2 min read

In Python, you cannot modify a dictionary while iterating over it using a for loop. This is because modifying the dictionary changes its size and can cause the loop to skip or repeat items, leading to unexpected behavior.

However, there are a few ways to delete items from a dictionary while iterating over it. One approach is to create a copy of the dictionary and iterate over the copy, while modifying the original dictionary. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
for key in list(my_dict.keys()):
    if key in ["a", "c"]:
        del my_dict[key]
print(my_dict)  # Output: {"b": 2, "d": 4}

In this example, we use the list() function to create a new list that contains a copy of the dictionary keys. We then iterate over this list using a for loop, and use the del statement to remove any keys that meet a certain condition (in this case, if the key is equal to “a” or “c”). Since we are modifying the original dictionary, we use the list() function to create a copy of the keys, so that we do not change the size of the dictionary while iterating over it.

Another approach is to use a dictionary comprehension to create a new dictionary that contains only the items that should be kept, based on a certain condition. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}
my_dict = {k: v for k, v in my_dict.items() if k not in ["a", "c"]}
print(my_dict)  # Output: {"b": 2, "d": 4}

In this example, we use a dictionary comprehension to create a new dictionary that contains only the key-value pairs from the original dictionary that do not have keys equal to “a” or “c”. This effectively removes those items from the dictionary.

Both of these approaches allow you to delete items from a dictionary while iterating over it, without causing unexpected behavior. However, it’s important to note that modifying a dictionary while iterating over it can be error-prone and should be done with caution. If possible, it’s often better to create a new dictionary that contains only the items that should be kept, rather than modifying the original dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply