How to count the key from the nested dictionary?

Viewed 31

I'd like to count and return the largest number of keys from the root('key1') to reach the end. How to compute and return the number of the deepest nest to the dictionary without using any libraries?

{'key1': {'key2': {'key3': {'key4': {'key5': {'key6': 'Y',
      'key7': 'N'}},
    'key8': {'key9': {'key10': 'Y', 'key11': 'N'}},
    'key12': {'key13': {'key14': 'N', 'key15': 'Y'}},
    'key16': {'key17': {'N': 'Y'}}}},
  'key18': {'key19': {'key20': 'N', 'key21': 'N', 'key22': 'N', 'key23': 'Y'}}}}

Under the case, I expect to return 6 as a counted number.

1 Answers

Here's a recursive solution that doesn't use any libraries (though there might be a better way to do this using collections):

def deepest_nesting(data):
    max_depth = 0
    if not isinstance(data, dict):
        return max_depth

    for v in data.values():
        path_depth = deepest_nesting(v)
        max_depth = max(path_depth, max_depth)
    
    return 1 + max_depth

This returns 6 for your example, 1 for {'key1': 0}, 0 for a non-dict, 4 for {'one': {'two': 0, 'three': 0, 'four': 0}, 'five': {'six': {'seven': 0, 'eight': 0, 'nine': {'ten': 0}}}}, etc.

Related