【问题标题】:Recursive depth of python dictionarypython字典的递归深度
【发布时间】:2012-03-21 06:51:10
【问题描述】:

生日,

我试图找到一个搜索字典的函数的递归深度,但我有点迷失了...... 目前我有类似的东西:

myDict = {'leve1_key1': {'level2_key1': {'level3_key1': {'level4_key_1': {'level5_key1':   'level5_value1'}}}}}

而且我想知道嵌套最多的字典的嵌套程度...所以我执行以下操作...

def dict_depth(d, depth):

    for i in d.keys():
        if type(d[i]) is dict:
            newDict = d[i]
            dict_depth(newDict, depth+1)
    return depth

print dict_depth(myDict, 0)

唯一的问题是,递归循环只返回最终值(0)的返回值。 如果我输入打印语句 for i in d.keys():那么我至少可以打印递归的最高值,但是返回值是另一回事...

我确定这很简单 - 我刚刚得到 jellybrain。

干杯

【问题讨论】:

  • 这里没有任何限制(可用内存除外)。每个嵌套字典都是一个新对象,对它的父对象一无所知。
  • 但是您的代码可能会遇到堆栈溢出。这与任何字典限制无关。

标签: python recursion dictionary


【解决方案1】:

确保将递归调用的结果分配给depth。此外,正如@amit 所说,考虑使用 max 以便您可以处理具有多个键值对(树状结构)的字典。

def dict_depth(d, depth=0):
    if not isinstance(d, dict) or not d:
        return depth
    return max(dict_depth(v, depth+1) for k, v in d.iteritems())

>>> myDict = {'leve1_key1': {'level2_key1': 
               {'level3_key1': {'level4_key_1': 
                  {'level5_key1':   'level5_value1'}}}}}
>>> dict_depth(myDict)
5

【讨论】:

  • 请注意,不使用max() 的深度,如果字典有1 个以上的键,您可能会用更小的值覆盖depth
  • @amit 我同意。从 OP 的代码开始总是很危险的 :-)
【解决方案2】:

您应该存储从递归调用返回的值,并返回找到的最大值,否则 - 您正在调用递归函数而不对返回值做任何事情! [并按预期返回 0,因为它从未更改过]

def dict_depth(d, depth):
    ret = depth 
    for i in d.keys():
        if type(d[i]) is dict:
            newDict = d[i]
            ret = max(dict_depth(newDict, depth+1),ret) #finding max and storing it
    return ret #returning the max found

【讨论】:

  • @RaymondHettinger:非常适合我并打印“4”。我在这里假设OP希望外部字典为“0”。
【解决方案3】:
MyDict = {'a': {'a1': {'a11': 5, 'a12':[{2:'a22'}], 'a13':{'a14':'a11'}}, 'a2': 6}, 'b':{7:{8:{9:{10:{11:'11'}}}}}, 'c': {'c1': 18, 'c2': 1}}

def find_depth(dep,val):
    if isinstance(val,dict):
        dep=dep+1
        for j in val:
            find_depth(dep,val[j])
        temp_depth.append(dep)
        dep=0
        return max(temp_depth)
    elif isinstance(val,list):
        for k in val:
            find_depth(dep,k)


max_depth={}
for i in MyDict:
    dep=0
    temp_depth=[]
    max_depth.update({i:(find_depth(dep,MyDict[i]))})
    print max_depth

如果连列表也包括在内,这里的代码也可以正常工作。

【讨论】:

    【解决方案4】:

    如果 Raymond Hettinger 是 THE R.H.,我不可能击败他 ;-) 但我找到了一个类似的解决方案,其中包含一些打印语句来说明正在发生的事情!

    d = {1: 2, 2: {3: {5: 6}}, 3: {4: 4}, 7: 8}
    def recursion_depth(dict_, depth):
        for k in dict_:
            print "key{0}:value{1} = depth:{2}".format(k, dict_[k], depth)
        if type(dict_[k]) == dict:
            actual_depth = recursion_depth(dict_[k], depth+1)
            if actual_depth > depth: depth += 1
        return depth
    
    >>>recursion_depth(d,0)
    key1:value2 = depth:0
    key2:value{3: {5: 6}} = depth:0
    key3:value{5: 6} = depth:1
    key5:value6 = depth:2
    key3:value{4: 4} = depth:1
    key4:value4 = depth:2
    key7:value8 = depth:2
    2
    

    【讨论】:

      【解决方案5】:

      非递归版本:

      def depth(d):
      
          depth=0
          q = [(i, depth+1) for i in d.values() if isinstance(i, dict)]
          max_depth = 0
          while (q):
              print q
              n, depth = q.pop()
              max_depth = max(max_depth, depth)
              q = q + [(i, depth+1) for i in n.values() if isinstance(i, dict)]
      
          print max_depth
      

      【讨论】:

        猜你喜欢
        • 2021-11-22
        • 1970-01-01
        • 2017-02-20
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多