Do Python 2.7 views make for / in and change work together?

Python docs give warnings about trying to change a dict, iterating over it. Does this apply to submissions?

I understand that the views are “live” in the sense that if you change the underlying dict, the view automatically reflects the change. I also know that the natural ordering of bits can change if items are added or removed. How does it work in conjunction with for / in? Can you safely modify a dict without messing up the loop?

d = dict()
# assume populated dict
for k in d.viewkeys():
    # possibly add or del element of d

Does the for / in loop execute all new elements? Does it skip elements (due to reordering)?

+4
source share
1 answer

, , . , , , .

, , :

>>> d = {'foo': 'bar'}
>>> for key in d.viewkeys():
...     d['spam'] = 'eggs'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
>>> d = {'foo': 'bar', 'spam': 'eggs'}
>>> for key in d.viewkeys():
...    del d['spam']
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

, , , .

+7

All Articles