Recursive depth of python dictionary

前端 未结 5 1708
一向
一向 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:42

    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
    

提交回复
热议问题