A python dictionary can be nested i.e., there are dictionaries within a dictionary. In this article we will see how to calculated the level of nesting in a dictionary when there is a nested dictionary.
With string conversion
In this approach we convert the entire dictionary into a string. Then we count the number of left { that indicate to which level the dictionaries are nested.
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)Output
Running the above code gives us the following result −
The depth of dictionary: 3
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.
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))Output
Running the above code gives us the following result −
The depth of dictionary: 3