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

如何在Python字典中删除点分格式多级key并自动清理空父节点

实现方案

核心思路

  • 先将点分隔的待删除路径拆分为键名列表,方便逐层定位嵌套层级
  • 用递归函数完成删除操作,逻辑如下:
    1. 若当前处理的路径只剩最后一个键,直接从当前层级字典中弹出该键
    2. 若路径还有多层,先向下递归处理子级字典
    3. 子级处理完成后,若子级字典已为空,则将当前层级对应的子级键也弹出
    4. 最终返回当前层级字典是否为空,供上层判断是否需要删除当前层级的键
  • 遍历所有待删除路径,逐个调用递归函数处理即可,自动适配任意深度的嵌套字典

完整实现代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:39:00