从 python 中的列表和字典嵌套中删除任意元素

remove an arbitrary element from a nest of lists and dicts in python

a = [ 
    {
        'b':[1,2,3]
    },{
        'c':{
            'd':'e',
            'f':'g'
        }
    } 
]
b = [0,'b',2]
c = [2,'c','f']

上面我想用bc中包含的键来销毁a中对应的元素。在这种情况下,del a[1]['b'][2] 代表 a,或 a[2]['c'].pop('f') 代表 c

在给定任意深度和树结构的情况下,是否有一种干净的方法可以做到这一点?

def nested_del(structure, del_spec):
    for item in del_spec[:-1]:  # Loop through all but the last element.
        structure = structure[item]  # Go further into the nested structure
    del structure[del_spec[-1]]  # Use the last element to delete the desired value

nested_del(a, b)
nested_del(a, c)