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:")

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

Sample Output:

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


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.

Follow us on Facebook and Twitter for latest update.