Fix Python – Modifying a Python dict while iterating over it

Question

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

(f and g are just some black-box transformations.)

In other words, we try to add/remove items to d while iterating over it using iteritems.

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


Answer

It is explicitly mentioned on the Python doc page (for Python 2.7) that

Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

Similarly for Python 3.

The same holds for iter(d), d.iterkeys() and 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 iter(d)).

This question is answered By – Raphaël Saint-Pierre

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0