Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python modifying dict entries in-place during iteration

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

like image 689
Andrew Sun Avatar asked Oct 15 '25 09:10

Andrew Sun


1 Answers

The internal structure of the dictionary is determined by the keys, and not the values. At least currently. This means that you can modify the value associated with a key, but adding or removing keys (which the first example's d[k + 1] = d[k] + 1 does) will cause problems.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!