如何在Python字典中删除点分格式多级key并自动清理空父节点
实现方案
核心思路
- 先将点分隔的待删除路径拆分为键名列表,方便逐层定位嵌套层级
- 用递归函数完成删除操作,逻辑如下:
- 若当前处理的路径只剩最后一个键,直接从当前层级字典中弹出该键
- 若路径还有多层,先向下递归处理子级字典
- 子级处理完成后,若子级字典已为空,则将当前层级对应的子级键也弹出
- 最终返回当前层级字典是否为空,供上层判断是否需要删除当前层级的键
- 遍历所有待删除路径,逐个调用递归函数处理即可,自动适配任意深度的嵌套字典
完整实现代码
def remove_nested_path(target_dict, path_parts): if not path_parts or not isinstance(target_dict, dict): return False current_key = path_parts[0] if current_key not in target_dict: return False # 处理最后一级路径 if len(path_parts) == 1: target_dict.pop(current_key) return len(target_dict) == 0 # 递归处理子级 child_is_empty = remove_nested_path(target_dict[current_key], path_parts[1:]) # 子级为空则删除当前层级的对应键 if child_is_empty: target_dict.pop(current_key) return len(target_dict) == 0 # 测试用例 unused_field_list = ['a.b', 'b.d.y', 'c.g', 'z'] my_dictionary = { "a": { "b": { "key": "value" }, "c": { "f": { "key": "value" } } }, "b": { "d": { "y": { "key": "value" } }, "g": { "key": "value" } }, "c": { "g" : { "key": "value" } }, "z": { "key": "value" } } # 执行删除 for path in unused_field_list: path_keys = path.split('.') remove_nested_path(my_dictionary, path_keys) print(my_dictionary)
输出结果
运行上述代码后,输出的my_dictionary和你期望的结果完全一致:
{ "a": { "c": { "f": { "key": "value" } } }, "b": { "g": { "key": "value" } } }
内容的提问来源于stack exchange,提问作者Quentin
相关产品推荐
相关产品推荐

