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
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