Home > Article > Backend Development > How to Safely Delete Items from a Dictionary During Iteration in Python?
Deleting Items from a Dictionary While Iterating in Python
When working with dictionaries in Python, there may be instances where you need to remove items that fulfill specific criteria during iteration. While intuitively, it might seem that iterating directly over the dictionary and deleting items as encountered would suffice, this approach is problematic.
Challenges with Direct Deletion during Iteration
In Python 3, directly deleting items from a dictionary while iterating over it raises a RuntimeError. This is because modifying the dictionary size during iteration causes the iterator to malfunction.
In Python 2, this direct deletion approach results in an error if the item to be deleted is the next item in the iteration sequence.
Solutions
To safely delete items from a dictionary while iterating, here are recommended solutions:
Python 3 :
Convert the dictionary keys to a list using list(mydict.keys()) before iteration. This allows you to iterate over the list while making changes to the dictionary:
<code class="python">for k in list(mydict.keys()): if mydict[k] == 3: del mydict[k]</code>
Python 2:
Utilize the keys() or items() methods to create a list of keys or tuples of key-value pairs, respectively. You can then safely iterate over these lists to remove items without disrupting the iterator:
<code class="python">for k in mydict.keys(): if k == 'two': del mydict[k]</code>
<code class="python">for k, v in mydict.items(): if v == 3: del mydict[k]</code>
The above is the detailed content of How to Safely Delete Items from a Dictionary During Iteration in Python?. For more information, please follow other related articles on the PHP Chinese website!