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

如何在Python中移除JSON文件中的指定键(含嵌套键)

解决Python迭代字典时修改导致的RuntimeError及嵌套键移除问题

你遇到的RuntimeError: dictionary changed size during iteration错误,核心原因是:在遍历data['extra']的键时直接修改了字典(用pop删除键),导致字典大小在迭代过程中改变,迭代器无法正常工作。

最简单的解决方案:直接指定键移除

既然明确知道要移除的嵌套键是region,完全不需要遍历所有键,直接对data['extra']调用pop方法即可,这也是最高效的方式:

import json

# 注意路径加r前缀,避免转义字符解析错误
with open(r"C:\Users\sam\Downloads\test\Sample.json") as data_file:
    data = json.load(data_file)
    # 移除外层的country键
    data.pop('country')
    # 直接移除extra里的region键,第二个参数None表示键不存在时不报错
    data['extra'].pop('region', None)
    print(data)

批量处理嵌套键的通用方案

如果后续需要移除多个嵌套键,或者需要遍历筛选目标键,可以遍历字典键的副本(将keys()转为列表),这样迭代的是固定的键列表,修改原字典不会影响迭代过程:

import json

with open(r"C:\Users\sam\Downloads\test\Sample.json") as data_file:
    data = json.load(data_file)
    data.pop('country')
    # 遍历键的列表副本,避免迭代时修改字典触发错误
    for key in list(data['extra'].keys()):
        if key == 'region':
            data['extra'].pop(key, None)
    print(data)

运行结果

两种方法都会输出符合预期的结果:

{
    "organization": "GeeksForGeeks",
    "city": "Noida",
    "extra": {
        "lat": "",
        "long": ""
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:52:45