Know the depth of a dictionary

后端 未结 4 2069
遇见更好的自我
遇见更好的自我 2020-12-16 10:21

Supposing we have this dict:

d = {\'a\':1, \'b\': {\'c\':{}}}

What would be the most straightforward way of knowing the nesting depth

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 11:08

    A non-recursive solution:

    def depth(d):
    
        depth=0
        q = [(i, depth+1) for i in d.values() if isinstance(i, dict)]
        max_depth = 0
        while (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
    

提交回复
热议问题