"dictionary changed size during iteration" 正在更新词典列表

"dictionary changed size during iteration" while updating a list of dictionaries

我有一个字典列表,如下所示:

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

现在,我想使用正则表达式将所有 {name} 替换为另一个字符串(比如“car”),并更新词典列表。这是代码:

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)

我知道正则表达式部分可以正常工作。但是,我收到此错误:

RuntimeError: dictionary changed size during iteration

我做错了什么?

.update(key=value) 向字典中插入一个新键,其中键是 字符串文字 'key' 和值 value(在上面那行)。

你应该使用括号来索引字典,而不是调用 .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)

无需使用正则表达式 - str 有两个 built-in 方法,formatformat_map,可以替换标有大括号的字段,例如您的示例代码:

msg = "Hello, {location}!"
print(msg.format(location="World"))

msg2 = "{greeting}, {place}!"
params = {"greeting": "Bonjour", "place": "Birmingham"}
print(msg2.format_map(params))

使用这个:

for dct in car_list:
    for key, value in dct.items():
        dct[key] = value.format(name="car")