如何查找包含字典列表的字典的深度?

时间:2021-04-23 15:27:52

标签: python json python-3.x algorithm dictionary

我想知道包含字典列表的字典的深度,我写了一个简单的代码,但问题是它在每一步都会增加深度计数器。

这是我作为示例的输入:

respons = {
    "root":{
        "Flow":[{
            "Name":"BSB1",
            "Output":[{
                "Name":"BSB2",
                "Output":[{
                    "Name":"BSB5",
                    "Output":[{
                        "Name":"BSB6",
                        "Output":[{
                            "Name":"BSB8",
                            "Output":[]
                        }]
                    },
                    {
                        "Name":"BSB7",
                        "Output":[]
                    }]
                }]
            },
            {
                "Name":"BSB3",
                "Output":[{
                    "Name":"BSB4",
                    "Output":[]
                }]
            }]
        }]
    }
}

def calculate_depth(flow,depth):
    depth+=1
    md = []
    if flow['Output']:
        for o in flow['Output']:
            print(o['BusinessUnit'])
            md.append(calculate_depth(o,depth))
        print(max(md))
        print(md)
        return max(md)
    else:
        return depth
        

print(calculate_depth(respons['root']['Flow'][0],0))


通常我希望这个 dict 最长分支的深度不要遍历所有分支并在每一步增加

编辑

期望的结果是这个结构:5 为什么 ? 它是最长的分支 BSB1 => BSB2 => BSB5 => BSB6 => BSB8

1 个答案:

答案 0 :(得分:1)

这个结构的深度是有争议的。您的代码(以及您缩进数据结构的方式)似乎表明您不想将中间列表计算为向路径添加级别。然而,如果你想访问深层数据,你会写

respons['root']['Flow'][0]['Output'][0]['Output'][0]
#                      ^^^          ^^^          ^^^ ...not a level?

并将其带到这棵树的叶子上:最深的 [] 是一个级别吗?

以下代码仅将 dicts 计算为添加到级别,并且仅当它们不为空时:

def calculate_depth(thing):
    if isinstance(thing, list) and len(thing):
        return 0 + max(calculate_depth(item) for item in thing)
    if isinstance(thing, dict) and len(thing):
        return 1 + max(calculate_depth(item) for item in thing.values())
    return 0

这会为示例数据打印 19:

print(calculate_depth(respons['root']['Flow'][0]))

适应您的需求。

相关问题