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



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

假设我有字典:d = {'a': {'b': {'c': 10, 'd': 4}}}

我知道我可以做到:del d['a']['b']['d']

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

对于使用相同输入访问值,这很容易:

def dict_get_path(dict_in: Dict, use_path: List):
# Get the value from the dictionary, where (eg)
# use_path=['this', 'path', 'deep'] -> dict_in['this']['path']['deep']
for p in use_path:
dict_in = dict_in[p]
return 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]]

最新更新