Asked By – NPE
Let’s say we have a Python dictionary
d, and we’re iterating over it like so:
for k, v in d.iteritems(): del d[f(k)] # remove some item d[g(k)] = v # add a new item
g are just some black-box transformations.)
In other words, we try to add/remove items to
d while iterating over it using
Is this well defined? Could you provide some references to support your answer?
See also How to avoid “RuntimeError: dictionary changed size during iteration” error? for the separate question of how to avoid the problem.
Now we will see solution for issue: Modifying a Python dict while iterating over it
It is explicitly mentioned on the Python doc page (for Python 2.7) that
iteritems()while adding or deleting entries in the dictionary may raise a
RuntimeErroror fail to iterate over all entries.
Similarly for Python 3.
The same holds for
d.itervalues(), and I’ll go as far as saying that it does for
for k, v in d.items(): (I can’t remember exactly what
for does, but I would not be surprised if the implementation called