I know that in the general case, it’s unsafe to mutate a dict while iterating over it:
d = {1: 2, 3: 4}
for k in d.keys():
d[k + 1] = d[k] + 1
This yields a RuntimeError
as expected. However, while reading the documentation for dict
, I found the following (emphasis mine):
Iterating views while adding or deleting entries in the dictionary may raise a
RuntimeError
or fail to iterate over all entries.
So I tried the following code:
d = {1: 2, 3: 4}
for k in d.keys():
d[k] = d[k] + 1
Note: I did not add or remove any entries during the iteration; I only updated existing entries. I've tried it with a few examples and so far have not received a RuntimeError
, and the loop works as expected.
Is this guaranteed to work by the language? Or have I just been lucky so far?
Note: I am using Python 3, so d.keys()
returns a dynamic view rather than a list
).