从python中的列表和dicts中删除任意元素

时间:2016-01-17 18:40:42

标签: python list dictionary nested

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]aa[2]['c'].pop('f')c

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

1 个答案:

答案 0 :(得分:2)

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)