Delete from nested dictionary
Made a function deepdelete which takes a list of keys and recursively deletes the leaf, followed by any branch dictionaries that are now empty:
def deepdelete(branch, keys):
if len(keys) > 1: # not at the leaf
empty = deepdelete(branch[keys[0]], keys[1:]) # recursion
if empty:
del branch[keys[0]] # delete branch
else: # at the leaf
del branch[keys[0]] # delete the leaf
return len(branch) == 0 # could return len
deepdelete(d, delkeys)
Passing in the dictionary you gave as example:
d = {0: {1: {0: {0: {0: {1: {0: {0: 4}}}}}}}}
deepdelete(d, (0, 1, 0, 0, 0, 1, 0, 0))
Outputs:
{}
Passing in a more interesting dictionary with other branches:
d = {0: {1: {0: {0: {0: {1: {0: {0: 4}}, 'no_delete': 2}, 'other_data': 3}, 'keep_me': 4}, 'special': 4}, 'preserve': 1}, 'important': 50}
deepdelete(d, (0, 1, 0, 0, 0, 1, 0, 0))
Outputs:
{0: {'preserve': 1, 1: {0: {0: {0: {'no_delete': 2}, 'other_data': 3}, 'keep_me': 4}, 'special': 4}}, 'important': 50}