Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find depth of a dictionary in Python
A Python dictionary can be nested, meaning there are dictionaries within dictionaries. In this article, we will see how to calculate the level of nesting in a dictionary when there are nested dictionaries.
Using String Conversion
In this approach, we convert the entire dictionary into a string and count the number of opening braces { to determine the nesting level ?
Example
dictA = {1: 'Sun', 2: {3: {4: 'Mon'}}}
dictStr = str(dictA)
cnt = 0
for i in dictStr:
if i == "{":
cnt += 1
print("The depth of dictionary:", cnt)
The output of the above code is −
The depth of dictionary: 3
Using Recursion
We can design a function that recursively calls 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 to calculate the maximum depth ?
Example
def finddepth(dictA):
if isinstance(dictA, dict):
return 1 + (max(map(finddepth, dictA.values()))
if dictA else 0)
return 0
dictA = {1: 'Sun', 2: {3: {4: 'Mon'}}}
print("The depth of dictionary:", finddepth(dictA))
The output of the above code is −
The depth of dictionary: 3
Using Iterative Approach with Queue
An iterative approach using a queue can also calculate dictionary depth without recursion ?
Example
from collections import deque
def find_depth_iterative(dictA):
if not isinstance(dictA, dict):
return 0
queue = deque([(dictA, 1)])
max_depth = 1
while queue:
current_dict, depth = queue.popleft()
max_depth = max(max_depth, depth)
for value in current_dict.values():
if isinstance(value, dict):
queue.append((value, depth + 1))
return max_depth
dictA = {1: 'Sun', 2: {3: {4: 'Mon'}}}
print("The depth of dictionary:", find_depth_iterative(dictA))
The output of the above code is −
The depth of dictionary: 3
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| String Conversion | O(n) | O(n) | Simple dictionaries |
| Recursion | O(n) | O(d) | Clean, readable code |
| Iterative | O(n) | O(w) | Avoiding recursion limits |
Conclusion
The recursive approach is the most elegant and widely used method for finding dictionary depth. Use the iterative approach when dealing with very deep dictionaries to avoid recursion limits.
