Ways to find the depth of a dictionary in Python

In this article, we are going to see the different methods to find the depth of a nested dictionary.

Let’s see how we can do this.

Method 1: Using recursion

In this method, the function dic_depth is called recursively, which returns the maximum depth of the current dictionary which is passed as input to the function.

See the code below

# Solution using recursion
def dic_depth(dic, depth = 1): 
    if isinstance(dic, dict) and dic: 
        return 1 + max(dic_depth(dic[key], depth) for key in dic) 
    return 0

if __name__ == "__main__": 
    
    # Example 1
    dic1 = {1:'Python', 2: {3: {4: {5:'C#'},6:'Java'},7:'C++'}} 
    print('Depth of dictionary 1->',dic_depth(dic1)) 
    
    # Example 2
    dic2 = {'fruits':{'peach':1,'mango':2,},'vegetable':{}} 
    print('Depth of dictionary 1->',dic_depth(dic2))

Output:

Depth of dictionary 1-> 4
Depth of dictionary 1-> 2

We can also use the map function to map the items of the current dictionary to the caller function.

See the code below.

# Solution using recursion
def dic_depth(dic, depth = 1): 
    if isinstance(dic, dict) and dic: 
        return 1 + max(map(dic_depth,dic.values())) 
    return 0

if __name__ == "__main__": 
    
    # Example 1
    dic1 = {1:'Python', 2: {3: {4: {5:'C#'},6:'Java'},7:'C++'}} 
    print('Depth of dictionary 1->',dic_depth(dic1)) 
    
    # Example 2
    dic2 = {'fruits':{'peach':1,'mango':2,},'vegetable':{}} 
    print('Depth of dictionary 1->',dic_depth(dic2))

Output:

Depth of dictionary 1-> 4 
Depth of dictionary 1-> 2

Method 2: Iterative

In iterative solution, we first create a list of the initial dictionary with its initial dept. Now we keep popping the items of the list and update the current max depth. We then insert the items of the current dictionary into the list with increased depth.

See the code below and try to understand it with the comments written in the code.

# Iterative solution
def dic_depth(Dict):     
    
    # initial depth
    initial_depth = 1
    
    # list containg intial dictionary object
    # and its initial depth
    obj_list = [(Dict,initial_depth)]
    
    # initialising maximum depth
    max_depth = 0
    
    # Iterate till the list
    # becomes empty
    while(obj_list): 
        
        # current dictionary object and its depth
        curr_dic , depth = obj_list.pop() 
        
        max_depth = max(max_depth, depth) 
        
        # Inserting the items of the
        # current dictionary if it is a dictionary instance
        # and increasing the depth by 1
        
        obj_list = obj_list + [(k, depth + 1) for k in curr_dic.values() 
                               if isinstance(k, dict)] 
        
    return max_depth 

if __name__ == "__main__": 
    
    # Example 1
    dic1 = {1:'Python', 2: {3: {4: {5:'C#'},6:'Java'},7:'C++'}} 
    print('Depth of dictionary 1->',dic_depth(dic1)) 
    
    # Example 2
    dic2 = {'fruits':{'peach':1,'mango':2,},'vegetable':{}} 
    print('Depth of dictionary 1->',dic_depth(dic2)) 

Output:

Depth of dictionary 1-> 4 
Depth of dictionary 1-> 2

Leave a Reply

Your email address will not be published. Required fields are marked *