Home >Backend Development >Python Tutorial >Can You Delete Items from a Python Dictionary During Iteration?
When manipulating dictionaries in Python, the question of deleting items while iterating over the keys arises. Here's how to achieve this effectively.
In Python 3, you can iterate over a list of keys obtained from the keys() method:
<code class="python">for k in list(mydict.keys()): if mydict[k] == 3: del mydict[k]</code>
In Python 2, the iterkeys() method returns an iterator instead of a list. Therefore, modifying the dictionary while iterating over iterkeys() raises a RuntimeError. Instead, use the keys() method to get a list of keys:
<code class="python">for k in mydict.keys(): if k == 'two': del mydict[k]</code>
For deleting based on item values, iterate over the items() method:
<code class="python">for k, v in mydict.items(): if v == 3: del mydict[k]</code>
Remember to be cautious when modifying dictionaries during iteration, as it can disrupt the iteration process.
The above is the detailed content of Can You Delete Items from a Python Dictionary During Iteration?. For more information, please follow other related articles on the PHP Chinese website!