如何找到多级python dict中最深的dict级别?

时间:2014-12-02 13:00:07

标签: python algorithm dictionary

例如,如果我们有一个类似{a: {b: c}, d: e}的字典,则此字典的最高级别为2.

我一直在考虑找出2天任意字典的最高级别的方法,但没有找到解决方案。

怎么做?

1 个答案:

答案 0 :(得分:2)

使用递归:

def nested_depth(d):
    if not isinstance(d, dict):
        return 0
    if not d:
        return 1
    return 1 + max(nested_depth(v) for v in d.values())