【问题标题】:How to find the maximum depth of a dictionary with lists taking a json object as input如何使用以json对象作为输入的列表查找字典的最大深度
【发布时间】:2021-01-07 20:44:45
【问题描述】:

我有一个 JSON 对象,我想编写一个 Python 程序,将其作为输入并计算其最大深度。

代码,

f = open(r"c:\python\8_DEPTH\JSON_Kino.JSON", "r")
x = f.read()

def depth(x):
    if type(x) is dict and x:
        return 1 + max(depth(x[a]) for a in x)
    if type(x) is list and x:
        return 1 + max(depth(a) for a in x)
    return 0
print(depth(x))

我的问题是当我运行程序时它计数为 0。有什么想法吗???

【问题讨论】:

  • x 总是一个字符串,这就是为什么你的函数总是返回 0
  • 欢迎来到 SO!显示您的 JSON 是个好主意。正如 Moinuddin 所说,您尚未将 JSON 字符串解析为 dict 或列表,因此该函数仅返回 0,因为两个分支都不为真。您的意思是先使用json.loads(x) 吗?
  • 您可以将答案标记为解决方案,但请不要在问题中输入(已解决)。见What should I do when someone answers my question?

标签: python arrays json nested-lists


【解决方案1】:

试试这个:

def depth(myDict): 
       
    str_dic = str(myDict) 
    counter = 0
    for i in str_dic: 
        if i == "{": 
            counter += 1
    return(counter) 
   

print (depth(myDict)) 

【讨论】:

  • 这是一个不错的技巧!如果其中一个字典包含一个带有{ 字符的字符串怎么办?
  • 感谢您的回答,但如果字典中还有一个列表,我也想计算深度。
猜你喜欢
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-17
  • 2021-05-11
  • 2014-10-06
  • 2018-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多