Problem with OrderedDict

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 30 08:55:39 EDT 2018


On Wed, 30 May 2018 05:03:02 -0400, Terry Reedy wrote:

> On 5/30/2018 4:48 AM, Frank Millman wrote:
>> Hi all
>> 
>> I want to work backwards to solve this problem, so I have to explain it
>> forwards to put you in the picture.
>> 
>> I have an Ordered Dictionary. Under certain circumstances I am getting
>> this error -
>> 
>>     RuntimeError: OrderedDict mutated during iteration
> 
> This should mean that the value associated with a key was sometimes
> changed.

I don't think so. It should be legal to iterate over a dict and change 
the values. At least it works for me:

import random
from collections import OrderedDict
d = OrderedDict(zip(range(1, 10), "abcdefghi"))
for i in range(10000):  # just in case of intermittent errors
    for value in d.values():
        d[random.randrange(1, 10)] = random.random()


I get no errors.



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