Home >Backend Development >Python Tutorial >Can You Delete Items from a Python Dictionary During Iteration?

Can You Delete Items from a Python Dictionary During Iteration?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 03:31:30732browse

Can You Delete Items from a Python Dictionary During Iteration?

Can You Remove Items from a 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.

Option for Python 3

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>

Option for Python 2

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn