Know the depth of a dictionary

后端 未结 4 2078
遇见更好的自我
遇见更好的自我 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

    Iterative solution:

    from collections import deque
    
    
    def depth(d):
        q = deque([d])
        q2 = deque()
        max_depth = 0
        while q:
            curr_dict = q.popleft()
            if isinstance(curr_dict, dict):
                for di in curr_dict.itervalues():
                    q2.append(di)
            if not q:
                q, q2 = q2, q
                max_depth += 1
        return max_depth
    
    print depth(None)
    print depth({})
    print depth({"a": "b"})
    print depth({"a": "b", "c": {"d": "e"}, "f": {"g": "h"}, "i": {"j": "k"}, "x": {}, "z": {} })
    print depth({'a':1, 'b': {'c':{}}})
    print depth({'foo': {'bar': {'baz': 0}, 'spam': {'ham': {'monty': 1}, 'eric': 'idle'}}, 'john': 'cleese'})
    

提交回复
热议问题