SZanlongo
7/8/2016 - 5:21 PM

Delete from nested dictionary From: https://stackoverflow.com/questions/21390243/how-to-delete-from-an-arbitrarilly-deeply-nested-dictionar

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}