Modifying a Python dict while iterating over it

dictionary, python

Solution

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)`).

Problem

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.

Original source

Related problems