Recursive depth of python dictionary

前端 未结 5 1716
一向
一向 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 12:41

    A non-recursive version:

    def depth(d):
    
        depth=0
        q = [(i, depth+1) for i in d.values() if isinstance(i, dict)]
        max_depth = 0
        while (q):
            print q
            n, depth = q.pop()
            max_depth = max(max_depth, depth)
            q = q + [(i, depth+1) for i in n.values() if isinstance(i, dict)]
    
        print max_depth
    

提交回复
热议问题