Dynamically delete an item from a nested dictionary

dictionary, nested, python

Solution

You can use a for-loop to go through the values in `key_list` and navigate to the sub-dictionary that you want to remove the item from:

sub = D                 # Start with the full dictionary
for i in key_list[:-1]:
    sub = sub[i]        # Move down a level

In the end, `sub` will be the dictionary that you want to alter. All you need to do now is:

del sub[key_list[-1]]

since `key_list[-1]` is the key to remove.

Below is a demonstration:

>>> D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}}
>>> key_list = ['key1', 'key2', 'key4']
>>> sub = D
>>> for i in key_list[:-1]:
...     sub = sub[i]
...
>>> del sub[key_list[-1]]
>>> D
{'key1': {'key5': 'value5', 'key2': {'key3': 'value3'}}}
>>>

As you can see, this is equivalent to:

>>> D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}}
>>> del D['key1']['key2']['key4']
>>> D
{'key1': {'key5': 'value5', 'key2': {'key3': 'value3'}}}
>>>

except that the solution is dynamic (no hard-coded keys).

Problem

I have a nested dictionary and I want to be able to delete an arbitrary key inside of it. The dictionary could look like this: ``` D={'key1':{'key2':{'key3':'value3', 'key4':'value4'}, 'key5':'value5'}} ``` But it could be of arbitrary size. The problem is that the keys should be taken from a "key list" looking, for example, like this: ``` key_list = ['key1', 'key2', 'key4'] ``` `key_list` could be of arbitrary size and have any of the dictionary's keys in it. Because of the above criteria, I can't just use: ``` del D['key1']['key2']['key4'] ``` because I can't know beforehand which keys that `key_list` will contain. So, how would a generic code look like that based on the content of `key_list`, deletes the corresponding item in the dictionary `D`?

Original source