首页 > 解决方案 > 如何计算嵌套字典中的键?

问题描述

我想从根('key1')计算并返回最大数量的键以到达末尾。如何在不使用任何库的情况下计算最深嵌套的数量并将其返回到字典中?

{'key1': {'key2': {'key3': {'key4': {'key5': {'key6': 'Y',
      'key7': 'N'}},
    'key8': {'key9': {'key10': 'Y', 'key11': 'N'}},
    'key12': {'key13': {'key14': 'N', 'key15': 'Y'}},
    'key16': {'key17': {'N': 'Y'}}}},
  'key18': {'key19': {'key20': 'N', 'key21': 'N', 'key22': 'N', 'key23': 'Y'}}}}

在这种情况下,我希望返回 6 作为计数。

标签: python-3.x

解决方案


这是一个不使用任何库的递归解决方案(尽管使用collections可能有更好的方法):

def deepest_nesting(data):
    max_depth = 0
    if not isinstance(data, dict):
        return max_depth

    for v in data.values():
        path_depth = deepest_nesting(v)
        max_depth = max(path_depth, max_depth)
    
    return 1 + max_depth

6将为您的示例返回 for 1{'key1': 0}0字典、4for{'one': {'two': 0, 'three': 0, 'four': 0}, 'five': {'six': {'seven': 0, 'eight': 0, 'nine': {'ten': 0}}}}等。


推荐阅读