You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何批量重命名字典key,解决迭代时修改大小报错问题

报错原因

你遍历字典items()的过程中直接向原字典新增键,会修改字典的结构,Python禁止在迭代字典时改变字典的大小,因此触发运行时错误:RuntimeError: 迭代过程中字典大小发生改变。同时你原代码仅新增了新键,没有删除旧的目标键,即使不报错也无法得到符合预期的字典。

修复方案

方案1:修改原字典

遍历原字典键的静态副本(转换为列表后遍历的内容不会随原字典变化),新增新键后删除旧键即可,代码如下:

# 将keys转为列表得到固定的遍历对象,避免迭代过程受字典修改影响
for key in list(file.keys()):
    name = key.split('.')
    num = name[0].split('(')
    image_num = num[1][:-1]
    replace1 = '1.5_Curry_Vegetables_'+image_num+'.'+name[1]

    file[replace1] = file[key]
    # 删除旧键
    del file[key]

方案2:生成新字典(不修改原字典)

如果需要保留原字典,可以直接生成替换完键的新字典,不会触发迭代报错:

new_file = {}
for key, value in file.items():
    name = key.split('.')
    num = name[0].split('(')
    image_num = num[1][:-1]
    replace1 = '1.5_Curry_Vegetables_'+image_num+'.'+name[1]
    new_file[replace1] = value

后续直接使用new_file即可。

内容的提问来源于stack exchange,提问作者sinG20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 19:54:03