How to find the maximum “depth” of a python dictionary or JSON object?

后端 未结 4 1192
栀梦
栀梦 2021-01-06 20:41

I have a json string and I want to know what its maximum depth is. By depth I mean the number of embedded keys. So if one key as 7 \"children\" and know other key had that

4条回答
  •  庸人自扰
    2021-01-06 21:20

    Here's one implementation:

    def depth(x):
        if type(x) is dict and x:
            return 1 + max(depth(x[a]) for a in x)
        if type(x) is list and x:
            return 1 + max(depth(a) for a in x)
        return 0
    

提交回复
热议问题