Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive depth of python dictionary

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 = {'leve1_key1': {'level2_key1': {'level3_key1': {'level4_key_1': {'level5_key1':   'level5_value1'}}}}}

And I want to know just how nested the most nested dictionary is... so I do the following...

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)

Only problem is, the recursive loop only returns the return of the final value (0). if I put in a print statement for i in d.keys(): then I can at least print the highest value of recursion, but returning the value is a different matter...

I'm sure this is straightforward - I've just got jellybrain.

like image 768
MandMBen Avatar asked Mar 02 '12 19:03

MandMBen


People also ask

What is the recursion depth in Python?

Python's default recursion limit is 1000, meaning that Python won't let a function call on itself more than 1000 times, which for most people is probably enough. The limit exists because allowing recursion to occur more than 1000 times doesn't exactly make for lightweight code.

How do you find the depth of a dictionary?

With recursion We can design a function that will recursively call itself to check the values of the dictionary. As long as the inner element is evaluated to be a dictionary, the function will call itself and we will get the result for the depth of the dictionary.

What is the recursion depth?

The maximal number of nested calls (including the first one) is called recursion depth. In our case, it will be exactly n . The maximal recursion depth is limited by JavaScript engine. We can rely on it being 10000, some engines allow more, but 100000 is probably out of limit for the majority of them.

Can Python dictionary be nested to any depth?

Dictionaries are mutable. Items are accessed by their position in a dictionary. A dictionary can contain any object type except another dictionary. Dictionaries can be nested to any depth.


3 Answers

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
like image 135
Raymond Hettinger Avatar answered Oct 04 '22 23:10

Raymond Hettinger


You should store the value retured from the recursive call, and return the max value found, otherwise - you are calling the recursive function without doing anything with the returned value! [and returning 0 as expected, since it was never changed]

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
like image 45
amit Avatar answered Oct 05 '22 01:10

amit


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

Here is code works fine if even list also included.

like image 26
ravikanth Avatar answered Oct 04 '22 23:10

ravikanth