Python 在嵌套字典中删除任意深度的键

Python 在嵌套字典中删除任意深度的键,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我的目标是从嵌套字典中删除一个值 def dict_del_path(dict_in: Dict, use_path: List): # Loop over all the keys except last for p in use_path[:-1]: dict_in = dict_in[p] # Delete using last key in path del dict_in[use_path[-1]] 假设我有字典:d={'a':{'b'

我的目标是从嵌套字典中删除一个值

def dict_del_path(dict_in: Dict, use_path: List):
    # Loop over all the keys except last
    for p in use_path[:-1]:
        dict_in = dict_in[p]
    # Delete using last key in path
    del dict_in[use_path[-1]]
假设我有字典:
d={'a':{'b':{'c':10,'d':4}}

我知道我能做到:
deld['a']['b']['d']

但我有一个嵌套键列表,长度未知。如果我有列表
['a','b','d']
,我想产生与上面相同的行为。问题是我不知道使用上述语法的键列表的长度

要使用相同的输入访问值,很容易:

def dict_get_path(dict_in:dict,use_path:List):
#从字典中获取值,其中(例如)
#在['this']['path']['deep']中使用[u path=['this','path','deep']->dict\u
对于正在使用的p\u路径:
dict_in=dict_in[p]
返回dict_in

但是我想不出任何类似的方法来删除一个条目而不重新构建整个字典。

使用相同的循环,除了在最后一个键之前停止。然后用它从最里面的字典中删除

def dict_del_path(dict_in: Dict, use_path: List):
    # Loop over all the keys except last
    for p in use_path[:-1]:
        dict_in = dict_in[p]
    # Delete using last key in path
    del dict_in[use_path[-1]]

使用相同的循环,但在最后一个关键点之前停止。然后用它从最里面的字典中删除

def dict_del_path(dict_in: Dict, use_path: List):
    # Loop over all the keys except last
    for p in use_path[:-1]:
        dict_in = dict_in[p]
    # Delete using last key in path
    del dict_in[use_path[-1]]

啊,我没有想到Python中的所有东西都是引用;降级到字典中仍然引用同一个字典,没有定义任何新的内容,所以这就是它工作的原因。简单的解决方案——谢谢!啊,我没有想到Python中的所有东西都是引用;降级到字典中仍然引用同一个字典,没有定义任何新的内容,所以这就是它工作的原因。简单的解决方案——谢谢!