使用Python dpath库删除嵌套对象并自动清理空父节点的方法
解决方案
dpath 原生的delete方法默认不会自动清理删除子键后变空的父节点,你可以封装一个带空父节点自动清理逻辑的删除函数实现需求,示例代码如下:
import dpath.util def delete_with_cleanup(dict_obj, path, separator="."): # 执行原生删除操作 dpath.util.delete(dict_obj, path, separator=separator) # 拆分路径获取所有上层父节点的分段 path_parts = path.split(separator)[:-1] # 从最下层父节点向上回溯校验 while path_parts: current_parent_path = separator.join(path_parts) try: parent_value = dpath.util.get(dict_obj, current_parent_path, separator=separator) # 父节点为空字典/空列表则删除 if isinstance(parent_value, (dict, list)) and len(parent_value) == 0: dpath.util.delete(dict_obj, current_parent_path, separator=separator) else: # 遇到非空父节点就终止回溯 break except KeyError: # 父节点已不存在直接终止 break path_parts.pop() # 测试逻辑 dictionary = { "a": { "b": { "c": 0, "d": 1, "e": 2 } } } # 逐个删除b节点下的所有子键 delete_with_cleanup(dictionary, "a.b.c") delete_with_cleanup(dictionary, "a.b.d") delete_with_cleanup(dictionary, "a.b.e") print(dictionary)
执行上述代码输出结果为{'a': {}},完全符合预期。
该函数兼容列表类型的父节点清理,每次删除操作后自动从下往上逐层检查父节点状态,无需额外手动处理空节点。
内容的提问来源于stack exchange,提问作者user8211795
相关产品推荐
相关产品推荐

