Home > front end >  "dictionary changed size during iteration" while updating a list of dictionaries
"dictionary changed size during iteration" while updating a list of dictionaries

Time:02-18

I have a list of dictionaries, which looks like this:

car_list = [
    {'Toyota': '{name}/Toyota'},
    {'Mazda':  '{name}/Mazda'},
    {'Nissan': '{name}/Nissan'}
]

Now, using a regex, I want to replace all {name}s with another string (say "car"), and update the list of dictionaries. This is the code:

regex = r'\{. ?\}'
for dic in car_list:
    for key, value in dic.items():
        for name in re.findall(regex, value):
            value = value.replace(name, "car")
        dic.update(key=value)

I know as a fact that the regex part is working. However, I get the "RuntimeError: dictionary changed size during iteration". What am I doing wrong?

CodePudding user response:

.update(key=value) inserts a new key into the dictionary where the key is the string literal 'key' and value value (as assigned in the line above).

You should use brackets to index into the dictionary, rather than calling .update():

for dic in car_list:
    for key, value in dic.items():
        for name in re.findall(regex, value):
            value = value.replace(name, "car")
        dic[key]=value

# Prints [{'Toyota': 'car/Toyota'}, {'Mazda': 'car/Mazda'}, {'Nissan': 'car/Nissan'}]
print(car_list)
  • Related