Reputation: 1623
My goal is to delete a value from a nested dictionary.
Say I have the dictionary: d = {'a': {'b': {'c': 10, 'd': 4}}}
.
I know that I could do: del d['a']['b']['d']
.
But I have a list of nested keys, of unknown length. I want to produce the same behavior as above if I have the list ['a', 'b', 'd']
. The problem is that I don't know the length of the list of keys to use the above syntax.
For accessing a value with the same input, it's easy:
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
But I can't figure out any analogous way to delete an item without re-constructing the whole dictionary.
Upvotes: 1
Views: 278
Reputation: 781350
Use the same loop, except stop before the last key. Then use that to delete from the innermost 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]]
Upvotes: 3