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

如何移除字典中的指定嵌套键?现有方法失效求解决办法

递归移除字典中指定键(含嵌套层级)

你原来的字典推导式只能处理顶层键,没法遍历嵌套的子字典,所以要通过递归的方式实现深层键的移除。

实现代码

acc = ["key1", "key_", "four"]
my_dict = {"key1": "something", "key_": "something2", "three": {"four": "remove this", "five": "dsadsdsas"}}

def filter_dict(target_dict, exclude_keys):
    return {
        k: filter_dict(v, exclude_keys) if isinstance(v, dict) else v
        for k, v in target_dict.items()
        if k not in exclude_keys
    }

result = filter_dict(my_dict, acc)
print(result)

代码说明

  • 定义递归函数filter_dict,遍历目标字典的每个键值对:
    1. 如果值是字典类型,就递归调用自身处理这个子字典,确保嵌套层级的键也能被过滤
    2. 只保留不在exclude_keys(即acc列表)中的键
  • 执行后会得到移除所有指定键的结果:{'three': {'five': 'dsadsdsas'}}

为什么原推导式无效

原推导式{key: value for key, value in dict.items() if key not in acc}仅遍历了字典的顶层键值对,不会进入three对应的子字典内部处理four键,所以无法移除嵌套层级的目标键。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:45:24