python - recursively deleting dict keys?

前端 未结 3 1485

I\'m using Python 2.7 with plistlib to import a .plist in a nested dict/array form, then look for a particular key and delete it wherever I see it.

When it

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 11:32

    def walk(d, badvalue, answer=None, sofar=None):
        if sofar is None:
            sofar = []
        if answer is None:
            answer = []
        for k,v in d.iteritems():
            if k == badvalue:
                answer.append(sofar + [k])
            if isinstance(v, dict):
                walk(v, badvalue, answer, sofar+[k])
        return answer
    
    def delKeys(d, badvalue):
        for path in walk(d, badvalue):
            dd = d
            while len(path) > 1:
                dd = dd[path[0]]
                path.pop(0)
            dd.pop(path[0])
    

    Output

    In [30]: d = {1:{2:3}, 2:{3:4}, 5:{6:{2:3}, 7:{1:2, 2:3}}, 3:4}
    
    In [31]: delKeys(d, 2)
    
    In [32]: d
    Out[32]: {1: {}, 3: 4, 5: {6: {}, 7: {1: 2}}}
    

提交回复
热议问题