如何移除字典中的指定嵌套键?现有方法失效求解决办法
递归移除字典中指定键(含嵌套层级)
你原来的字典推导式只能处理顶层键,没法遍历嵌套的子字典,所以要通过递归的方式实现深层键的移除。
实现代码
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,遍历目标字典的每个键值对:- 如果值是字典类型,就递归调用自身处理这个子字典,确保嵌套层级的键也能被过滤
- 只保留不在
exclude_keys(即acc列表)中的键
- 执行后会得到移除所有指定键的结果:
{'three': {'five': 'dsadsdsas'}}
为什么原推导式无效
原推导式{key: value for key, value in dict.items() if key not in acc}仅遍历了字典的顶层键值对,不会进入three对应的子字典内部处理four键,所以无法移除嵌套层级的目标键。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

