w3resource

Python: Get the depth of a dictionary

Python dictionary: Exercise-54 with Solution

Write a Python program to get the depth of a dictionary.

Sample Solution:

Python Code:

# Define a function 'dict_depth' that calculates the depth (maximum nesting level) of a dictionary.
def dict_depth(d):
    # Check if the input 'd' is a dictionary.
    if isinstance(d, dict):
        # If 'd' is a dictionary, return 1 plus the maximum depth of its values (recursively).
        return 1 + (max(map(dict_depth, d.values())) if d else 0)
    # If 'd' is not a dictionary, return 0 (indicating no nesting).
    return 0

# Create a dictionary 'dic' with nested dictionaries to test the depth calculation.
dic = {'a': 1, 'b': {'c': {'d': {}}}}

# Print a message indicating the start of the code section and the dictionary being analyzed.
print("\nOriginal Dictionary:")
print(dic)

# Call the 'dict_depth' function to calculate the depth of the dictionary and print the result.
print(dict_depth(dic)) 

Sample Output:

Original Dictionary:
{'a': 1, 'b': {'c': {'d': {}}}}
4

Flowchart:

Flowchart: Get the depth of a dictionary

Python Code Editor:

Previous: Find the length of a given dictionary values.
Next: Access dictionary key’s element by index.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-54.php