How do I traverse and search a python dictionary?

前端 未结 7 1013
逝去的感伤
逝去的感伤 2020-12-04 18:52

I have nested dictionaries:

{\'key0\': {\'attrs\': {\'entity\': \'p\', \'hash\': \'34nj3h43b4n3\', \'id\': \'4130\'},
          u\'key1\': {\'attrs\': {\'ent         


        
相关标签:
7条回答
  • 2020-12-04 19:23

    Since recursion is known to be limited in python (see What is the maximum recursion depth in Python, and how to increase it?) I would rather have a loop based answer to this question, so the answer can be adapted to any level of depth in the dictionary. For that, the function

    def walkDict( aDict, visitor, path=() ):
        for  k in aDict:
            if k == 'attrs':
                visitor( path, aDict[k] )
            elif type(aDict[k]) != dict:
                pass
            else:
                walkDict( aDict[k], visitor, path+(k,) )
    

    Can be replaced by:

    def walkDictLoop(aDict, visitor, path=()):
        toProcess = [(aDict, path)]
        while toProcess:
            dictNode, pathNode = toProcess.pop(0)
            for k in dictNode:
                if k == 'attrs':
                    visitor(pathNode, dictNode[k])
                if isinstance(dictNode[k], dict):
                    toProcess.append( (dictNode[k], pathNode+(k,)) )
    
    0 讨论(0)
提交回复
热议问题