Know the depth of a dictionary

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

    You need to create a recursive function:

    >>> def depth(d):
    ...     if isinstance(d, dict):
    ...         return 1 + (max(map(depth, d.values())) if d else 0)
    ...     return 0
    ...
    >>> d = {'a':1, 'b': {'c':{}}}
    >>> depth(d)
    3
    

提交回复
热议问题