Python | Find depth of a dictionary
Last Updated :
27 Apr, 2023
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 Approach 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
# 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))
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
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
# 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))
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
# 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))
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
# 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))
Approach #4: Using a stack: You can use a stack to keep track of the current depth and iterate over the dictionary to find the maximum depth.
The dict_depth() function takes in a dictionary as an argument and returns the depth of the dictionary, i.e. the number of nested dictionaries within the original dictionary.
The function starts by initializing a stack with the first key-value pair in the dictionary and a depth of 1. It also initializes a variable max_depth to 1.
Then, the function enters a while loop that iterates over the stack. At each iteration, the function pops the key-value pair from the top of the stack and assigns the values to the variables curr_dict and depth, respectively.
Next, the function iterates over the key-value pairs in curr_dict using a for loop. For each key-value pair, if the value is a dictionary, the function adds the dictionary and the current depth + 1 to the stack. This allows the function to keep track of the depth as it iterates over the nested dictionaries.
Finally, the function updates the maximum depth using the max() function and returns it at the end of the function.
Python3
def dict_depth(dic):
# Initialize a stack with the first key-value pair in the dictionary
stack = [(dic, 1)]
# Initialize the maximum depth
max_depth = 1
# Iterate over the stack
while stack:
# Pop the key-value pair from the top of the stack
curr_dict, depth = stack.pop()
# If the value is a dictionary, add its key-value pairs to the stack
for key, value in curr_dict.items():
if isinstance(value, dict):
stack.append((value, depth + 1))
# Update the maximum depth
max_depth = max(max_depth, depth)
# Return the maximum depth
return max_depth
dic = {1:'a', 2: {3: {4: {}}}}
print(dict_depth(dic))
#This code is contributed by Edula Vinay Kumar Reddy
Time complexity: O(n)
Auxiliary Space: O(n)
Approach#6: using queue
This approach involves using a queue to perform a breadth-first search (BFS) on the dictionary. We start by adding the dictionary to the queue along with a depth of 1. Then we pop the first element from the queue, and for each key in the element, we add the corresponding value to the queue along with the depth of the parent element plus 1. We repeat this process until the queue is empty, and the maximum depth found so far is the depth of the dictionary.
Algorithm
- Initialize depth to 0 and create an empty queue
- Add the input dictionary and a depth of 1 to the queue
- While the queue is not empty:
- Pop the first element from the queue
- For each key in the element, add the corresponding value to the queue along with the depth of the parent element plus 1
- Update depth if the new depth is greater than the current depth
- Return depth.
Python3
from collections import deque
def find_depth(d):
if not isinstance(d, dict):
return 0
depth = 0
q = deque([(d, 1)])
while q:
node, node_depth = q.popleft()
depth = max(depth, node_depth)
for key in node:
if isinstance(node[key], dict):
q.append((node[key], node_depth + 1))
return depth
d = {1:'a', 2: {3: {4: {}}}}
print(find_depth(d))
Time Complexity: O(n), where n is the number of nodes in the dictionary.
Space Complexity: O(w), where w is the maximum width of the dictionary. In the worst case, the entire dictionary will be added to the queue, which can lead to a space complexity of O(n).
Similar Reads
How to Create a Dictionary in Python
The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
3 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys.How to Loop Through a Dictionary in PythonThere are multipl
6 min read
Python - Access Dictionary items
A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets.Example:Pythona = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value assosiated with "geeks" x = a["geeks"] print
3 min read
Python Nested Dictionary
A Dictionary in Python works similarly to the Dictionary in the real world. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. What is Python in Nested Dictionary? Nesting Dictionary means
3 min read
Convert a list of Tuples into Dictionary - Python
Converting a list of tuples into a dictionary involves transforming each tuple, where the first element serves as the key and the second as the corresponding value. For example, given a list of tuples a = [("a", 1), ("b", 2), ("c", 3)], we need to convert it into a dictionary. Since each key-value p
3 min read
Add new keys to a dictionary in Python
In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
Get length of dictionary in Python
Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Letâs explore the various methods.Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in d
3 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Filter Dictionary of Tuples by Condition - Python
This task involves filtering the items of a dictionary based on a specific condition applied to the values, which are tuples in this case. We will check certain conditions for each tuple in the dictionary and select the key-value pairs that satisfy the condition.Given the dictionary a = {'a': (6, 3)
3 min read
Python | Convert list of tuple into dictionary
Given a list containing all the element and second list of tuple depicting the relation between indices, the task is to output a dictionary showing the relation of every element from the first list to every other element in the list. These type of problems are often encountered in Coding competition
8 min read