Recursive depth of python dictionary

前端 未结 5 1741
一向
一向 2020-12-06 12:24

G\'day,

I am trying to find the recursive depth of a function that trawls a dictionary and I\'m a bit lost... Currently I have something like:

myDict         


        
5条回答
  •  囚心锁ツ
    2020-12-06 12:50

    I can't possible beat Raymond Hettinger, if he is THE R.H. ;-) But i came to a similar solution with some print statements to illustrate what's happening!

    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
    

提交回复
热议问题