Python删除字典嵌套key报list indices must be integers not str如何解决
错误原因分析
你定义的section_del需要两个入参name和section,但调用时仅传入了一个非法表达式['two']['Bad']:['two']会创建一个仅包含字符串"two"的列表,紧接着用['Bad']对列表做索引,自然抛出list indices must be integers or slices, not str的报错。
两层嵌套字典的删除实现
修改调用传参逻辑,同时给函数增加键存在性判断避免删不存在的键时报错:
sections = {} def section_add(name, section): sections[name] = section def section_del(name: str, section_key: str) -> bool: # 提前判断层级键是否存在,避免抛出KeyError if name in sections and section_key in sections[name]: del sections[name][section_key] return True return False one = {'one_1': ""} two = {'two_1': '2','Bad': 'delete'} section_add('one', one) section_add('two', two) # 正确调用方式,传入两个独立参数 section_del('two', 'Bad') print(sections) # 输出:{'one': {'one_1': ''}, 'two': {'two_1': '2'}}
任意层级嵌套字典的迭代删除实现
支持传入嵌套键的路径列表,迭代遍历层级完成删除,无递归栈溢出风险:
def nested_dict_delete(target_dict: dict, key_path: list) -> bool: """ 迭代删除嵌套字典中指定路径的键值对 :param target_dict: 要操作的目标字典 :param key_path: 嵌套键的路径列表,例如要删除dict['a']['b']['c']就传['a','b','c'] :return: 删除成功返回True,路径不存在返回False """ current = target_dict # 遍历到倒数第二个键,确认每一层都存在且是字典类型 for i in range(len(key_path) - 1): key = key_path[i] if key not in current or not isinstance(current[key], dict): return False current = current[key] # 对最后一级键执行删除 final_key = key_path[-1] if final_key in current: del current[final_key] return True return False # 测试示例 test_dict = { 'level1': { 'level2': { 'level3': '要删除的值', 'keep': '保留的值' } } } # 删除三级嵌套的key nested_dict_delete(test_dict, ['level1', 'level2', 'level3']) print(test_dict) # 输出:{'level1': {'level2': {'keep': '保留的值'}}} # 适配你的sections场景,删除sections['two']['Bad']调用方式如下 # nested_dict_delete(sections, ['two', 'Bad'])
内容的提问来源于stack exchange,提问作者user3732793
相关产品推荐
相关产品推荐

