How to delete items from a dictionary while iterating over it with Python?

Sometimes, we want to delete items from a dictionary while iterating over it with Python.

In this article, we’ll look at how to delete items from a dictionary while iterating over it with Python.

How to delete items from a dictionary while iterating over it with Python?

To delete items from a dictionary while iterating over it with Python, we can use the del operator.

For instance, we write

for k in list(my_dict.keys()):
    if mydict[k] == 3:
        del mydict[k]

to loop through the keys in the my_dict dictionary that we get from the keys method.

Then we check if mydict[k] is 3 and we delete the entry if it’s true.

Conclusion

To delete items from a dictionary while iterating over it with Python, we can use the del operator.