It's often necessary to modify the contents of a dictionary while iterating over it. However, deleting items directly during iteration can lead to errors or inconsistent results.
In Python 2, deleting items with del while iterating can cause issues because the iterator expects the dictionary's size to remain constant. This behavior results in a RuntimeError. Using the keys or items methods is recommended instead:
<code class="python">for k in mydict.keys(): if k == val: del mydict[k] # or for k, v in mydict.items(): if v == val: del mydict[k]</code>
In Python 3 , mydict.keys() returns an iterator, not a list. Modifying the dictionary during iteration will cause a RuntimeError. To avoid this, convert the iterator to a list before using del:
<code class="python">for k in list(mydict.keys()): if mydict[k] == 3: del mydict[k]</code>
Another option is to use the pop() method to remove items:
<code class="python">while mydict: k, v = mydict.popitem() if v == 3: mydict[k] = v # or for k in mydict.copy(): if mydict[k] == 3: mydict.pop(k)</code>
For Python 3 , using the keys or items methods with a list conversion is recommended to avoid runtime errors. For Python 2, the keys or items methods should be used directly to modify the dictionary safely.
The above is the detailed content of How Can I Safely Delete Items From a Dictionary While Iterating in Python?. For more information, please follow other related articles on the PHP Chinese website!