"Steven D'Aprano" wrote in message news:peorib$1f4$2...@blaine.gmane.org...
On Thu, 31 May 2018 10:05:43 +0200, Frank Millman wrote: > From the interpreter session below, you will see that adding a key while > processing the *last* key in an OrderedDict does not give rise to an > exception. If you mutate the dict, and then stop iterating over it, there is no check that the dict was mutated. It isn't an error to mutate the dict. It is an error to mutate it while it is being iterated over. If you stop the iteration, there's no problem.
Agreed, but my gut feel, and the following example, suggest that when processing the last key in a dictionary while iterating over it, you have not yet stopped iterating.
d = {} d[1] = 'one' d[2] = 'two' for k in d:
... if k == 2: ... d[3] = 'three' ... Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: dictionary changed size during iteration
OrderedDict seems to behave differently in this regard -
from collections import OrderedDict as OD d = OD() d[1] = 'one' d[2] = 'two' for k in d:
... if k == 2: ... d[3] = 'three' ...
d
OrderedDict([(1, 'one'), (2, 'two'), (3, 'three')])
Frank -- https://mail.python.org/mailman/listinfo/python-list