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
Be sure to assign the result of the recursive call to depth. Also, as @amit says, consider using max so that you can handle dicts with multiple key value pairs (a treelike structure).
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