python-3.x - 如何计算嵌套字典中的键?
问题描述
我想从根('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 作为计数。
解决方案
这是一个不使用任何库的递归解决方案(尽管使用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
字典、4
for{'one': {'two': 0, 'three': 0, 'four': 0}, 'five': {'six': {'seven': 0, 'eight': 0, 'nine': {'ten': 0}}}}
等。
推荐阅读
- c++ - 如何在 C++ 中的链表结构内实现堆栈数据类型?
- r - 使用线性模型进行预测和 data.frame 的重要性
- postgresql - 为什么我的 PostgreSQL 在 CURRENT_TIMESTAMP 中没有显示毫秒?
- javascript - ReactJS,没有在控制台上获得输出
- java - 如何解决这个问题 - HTTP 状态 500 – 内部服务器错误
- .htaccess - 需要 htaccess 专家 > 重定向到子目录 + 重写 URL
- docker - minikube docker 中的问题 --> 错误:http://nl.alpinelinux.org/alpine/v3.5/main:DNS 查找错误 #560
- javascript - 为什么不能在用 let 和 const 声明变量之前进行赋值?
- laravel - Laravel excel maatwebsite 导入,excel 单元格中的日期列返回为未知格式数字。如何解决这个问题?
- java - android studio中的两种风格