Modifying a Python dict while iterating over it Ask Question

Modifying a Python dict while iterating over it Ask Question

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.

ベストアンサー1

Alex Martelli weighs in on this here.

It may not be safe to change the container (e.g. dict) while looping over the container. So del d[f(k)] may not be safe. As you know, the workaround is to use d.copy().items() (to loop over an independent copy of the container) instead of d.iteritems() or d.items() (which use the same underlying container).

It is okay to modify the value at an existing index of the dict, but inserting values at new indices (e.g. d[g(k)] = v) may not work.

おすすめ記事