【问题标题】:How to find the depth of a dictionary that contains a list of dictionaries?如何找到包含字典列表的字典的深度?
【发布时间】:2021-04-23 15:27:52
【问题描述】:

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

这是我作为示例的输入:

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))


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

编辑

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

【问题讨论】:

  • 您能补充一下想要的结果吗?也就是说,问题中字典的预期深度是多少(最好解释原因)。此外,您能否编辑您的问题以包含您的代码返回的内容(以及为什么这不是预期的结果)?
  • @NikolaosChatzis 我更新了问题谢谢你在高级

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


【解决方案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]))

适应您的需要。

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多