Problem with OrderedDict - progress report
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Jun 1 07:22:04 EDT 2018
On Thu, 31 May 2018 16:37:39 +0200, Frank Millman wrote:
[...]
> 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'
Before Python 3.7, regular dicts are unordered. Just because you add 2
last, doesn't mean that 2 is the last item. The position of each item is
unpredictable, and 2 could end up in the first position.
In this example:
>>>> 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
just because k == 2 does not mean this matches on the last iteration. It
could be the first.
> OrderedDict seems to behave differently in this regard -
Neither OrderedDict nor dict guarantee to detect all mutations.
--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson
More information about the Python-list
mailing list