查找 Python 中字典的深度
Python 字典可以嵌套,即在一个字典中存在字典。本文将探讨在存在嵌套字典时如何计算字典的嵌套层级。
使用字符串转换
在此方法中,我们将整个字典转换为字符串。然后我们计算左大括号 { 的数量,该数量指示字典嵌套到哪个层级。
示例
dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
dictStr = str(dictA)
cnt = 0
for i in dictStr :
if i == "{":
cnt += 1
print("The depth of dictionary: ",cnt)输出
运行上述代码得到以下结果 −
The depth of dictionary: 3
使用递归
我们可以设计一个函数,该函数将递归调用自身来检查字典中的值。只要内部元素被评估为字典,该函数就会自身调用,并且我们将得到字典深度的结果。
示例
def finddepth(dictA):
if isinstance(dictA, dict):
return 1 + (max(map(finddepth, dictA.values()))
if dictA else 0)
return 0
dictA = {1: 'Sun', 2: {3: {4:'Mon'}}}
print("The depth of dictionary: ",finddepth(dictA))输出
运行上述代码得到以下结果 −
The depth of dictionary: 3
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP