Home > Net >  How to retrieve the depth of nested dictionaries in nested dictionaries in Python?
How to retrieve the depth of nested dictionaries in nested dictionaries in Python?

Time:11-19

I'm not sure if I'm just having a brainblock here or if this is actually supposed to be a challenge, but I am having trouble figuring out how to check the depth of nested dictionaries if the keys are not known.

Here is an example of what I am trying to do (in the most simple/efficient way):

Optimally, there would be some way for me to determine the maximum depth of this dict, without knowing the keys and values -

nested_dict = {
  'nest1': {
    'nest2': {
       'nest3': 'val'
    },
    'unknown_key', 'val',
    'unknown_key': 'val'
  }
}

Please let me know if this makes sense.

CodePudding user response:

Check if its a dict, if so, iterate over the values and recursively call the function get the max of the value.

PS : Dict was a syntax error, fixed it

def max_depth(d):
    if isinstance(d, dict):
        return 1   max((max_depth(value) for value in d.values()), default=0)
    return 0

nested_dict = {'nest1': {'nest2': {'nest3': 'val'}, 'unknown_key': 'val', 'unknown_key': 'val'}}


print(max_depth(nested_dict))

Output 3

  • Related