How to completely traverse a complex dictionary of unknown depth?

后端 未结 7 1954
深忆病人
深忆病人 2020-11-30 17:35

Importing from JSON can get very complex and nested structures. For example:

{u\'body\': [{u\'declarations\': [{u\'id\': {u\'name\': u\'i\',
            


        
相关标签:
7条回答
  • 2020-11-30 18:38

    Maybe can help:

    def walk(d):
        global path
          for k,v in d.items():
              if isinstance(v, str) or isinstance(v, int) or isinstance(v, float):
                path.append(k)
                print "{}={}".format(".".join(path), v)
                path.pop()
              elif v is None:
                path.append(k)
                ## do something special
                path.pop()
              elif isinstance(v, dict):
                path.append(k)
                walk(v)
                path.pop()
              else:
                print "###Type {} not recognized: {}.{}={}".format(type(v), ".".join(path),k, v)
    
    mydict = {'Other': {'Stuff': {'Here': {'Key': 'Value'}}}, 'root1': {'address': {'country': 'Brazil', 'city': 'Sao', 'x': 'Pinheiros'}, 'surname': 'Fabiano', 'name': 'Silos', 'height': 1.9}, 'root2': {'address': {'country': 'Brazil', 'detail': {'neighbourhood': 'Central'}, 'city': 'Recife'}, 'surname': 'My', 'name': 'Friend', 'height': 1.78}}
    
    path = []
    walk(mydict)
    

    Will produce output like this:

    Other.Stuff.Here.Key=Value 
    root1.height=1.9 
    root1.surname=Fabiano 
    root1.name=Silos 
    root1.address.country=Brazil 
    root1.address.x=Pinheiros 
    root1.address.city=Sao 
    root2.height=1.78 
    root2.surname=My 
    root2.name=Friend 
    root2.address.country=Brazil 
    root2.address.detail.neighbourhood=Central 
    root2.address.city=Recife 
    
    0 讨论(0)
提交回复
热议问题