Is replacing a value during iteration of a mapping safe in Python?

Neil G :

Is code like this guaranteed to work in Python?

d = {k: 2 * k for k in range(10)}

for k, v in d.items():
    d[k] = v + 1

As far as I know, deleting a key doesn't work, and neither does adding a key?

I know that I can work around this problem by rebuilding the dict (by using a comprehension, for example).

Edit: I'm looking for a reference showing this to be guaranteed to work in Python (not, for example, that it happens to work in the current implementation of CPython).

Heap Overflow :

The documentation warns about adding and deleting:

Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

If changing the value for an existing key were also dangerous, I'm sure they'd mention that as well.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=169416&siteId=1