Python | Find depth of a dictionary
Prerequisite: Nested dictionary
The task is to find the depth of given dictionary in Python. Let’s discuss all different methods to do this task.
Examples:
Input : {1:'a', 2: {3: {4: {}}}} Output : 4 Input : {'a':1, 'b': {'c':'geek'}} Output : 3
Approach #1 : Naive Alpproach
A naive approach in order to find the depth of a dictionary is to count the number of opening curly braces. But, one drawback of this approach is that it would only work if the input is correct.
# Python3 Program to find depth of a dictionary def dict_depth(dic, level = 1 ): str_dic = str (dic) counter = 0 for i in str_dic: if i = = "{" : counter + = 1 return (counter) # Driver code dic = { 1 : 'Geek' , 2 : { 3 : { 4 : {}}}} print (dict_depth(dic)) |
4
Approach #2: Using recursion
In this method we use recursion with max() function which picks the greatest depth for the current dictionary under scrutiny at each level.
# Python3 Program to find depth of a dictionary def dict_depth(dic, level = 1 ): if not isinstance (dic, dict ) or not dic: return level return max (dict_depth(dic[key], level + 1 ) for key in dic) # Driver code dic = { 1 : 'a' , 2 : { 3 : { 4 : {}}}} print (dict_depth(dic)) |
4
Another version of the recursive solution is to use map() function by which the values of the inner dictionary is mapped to the called function.
# Python3 Program to find depth of a dictionary def dict_depth(my_dict): if isinstance (my_dict, dict ): return 1 + ( max ( map (dict_depth, my_dict.values())) if my_dict else 0 ) return 0 # Driver code my_dict = { 1 : 'a' , 2 : { 3 : { 4 : {}}}} print (dict_depth(my_dict)) |
4
Approach #3: Iterative Solution
In this approach, we save the nested key and its initial depth in a variable, say p_dict
. Now, start a loop for p_dict
, and keep popping values while digging deeper for nested dictionaries.
# Python3 Program to find depth of a dictionary def dict_depth(myDict): Ddepth = 1 obj = [(k, Ddepth + 1 ) for k in myDict.values() if isinstance (k, dict )] max_depth = 0 while (obj): n, Ddepth = obj.pop() max_depth = max (max_depth, Ddepth) obj = obj + [(k, Ddepth + 1 ) for k in n.values() if isinstance (k, dict )] return max_depth # Driver code myDict = { 1 : 'a' , 2 : { 3 : { 4 :{}}}} print (dict_depth(myDict)) |
4