Home > Article > Backend Development > Can You Safely Modify a Dictionary While Iterating with `iteritems()` in Python?
Can Iterated Dictionaries Safely Modify Underlying Items?
When traversing a Python dictionary using iteritems(), modifications to the dictionary may lead to unexpected results. Removing items (e.g., del d[f(k)]) may trigger a "RuntimeError: dictionary changed size during iteration."
Official Documentation:
According to the Python documentation, one should not modify the dictionary during iteration. The iteritems() method iterates through the dictionary's copy of keys and values, but not the underlying dictionary itself. Hence, direct modifications to the dictionary (such as deletion or addition of items) will not be reflected in the iterator.
Safe Practices:
To avoid this issue, the documentation suggests using d.copy().items() to create an independent copy of the dictionary before iterating. Alternatively, one can iterate through a list of keys and use del d[key] or d[key] = newValue within the loop.
Partial Modification:
While adding items to new keys may cause issues, modifying existing values is generally safe. However, note that modifying the value at an existing key may change its hash value, potentially affecting its position in the dictionary.
The above is the detailed content of Can You Safely Modify a Dictionary While Iterating with `iteritems()` in Python?. For more information, please follow other related articles on the PHP Chinese website!