Recursive depth of python dictionary

前端 未结 5 1711
一向
一向 2020-12-06 12:24

G\'day,

I am trying to find the recursive depth of a function that trawls a dictionary and I\'m a bit lost... Currently I have something like:

myDict         


        
5条回答
  •  [愿得一人]
    2020-12-06 13:05

    MyDict = {'a': {'a1': {'a11': 5, 'a12':[{2:'a22'}], 'a13':{'a14':'a11'}}, 'a2': 6}, 'b':{7:{8:{9:{10:{11:'11'}}}}}, 'c': {'c1': 18, 'c2': 1}}
    
    def find_depth(dep,val):
        if isinstance(val,dict):
            dep=dep+1
            for j in val:
                find_depth(dep,val[j])
            temp_depth.append(dep)
            dep=0
            return max(temp_depth)
        elif isinstance(val,list):
            for k in val:
                find_depth(dep,k)
    
    
    max_depth={}
    for i in MyDict:
        dep=0
        temp_depth=[]
        max_depth.update({i:(find_depth(dep,MyDict[i]))})
        print max_depth
    

    Here is code works fine if even list also included.

提交回复
热议问题