How to find how many level of dictionary is there in Python

Question:

for example:

d = {1:{'name':'x', 'age':24, 'address':{'country':'zzz', 'zip':12345}}, 2:{'name':'y', 'age':21, 'address':{'country':'yyy', 'zip':54321}}, 3:{'name':'z', 'age':25}}

How can we find in an optimized way that we have maximum 3 layers(dictionary inside dictionary) of dictionary there.

Asked By: dpd

||

Answers:

You can use a recursive function to find the max depth of a nested dictionary:

def depth(d):
    if (not isinstance(d, dict) or not d):
        return 0
    else:
        return max(depth(v) for k, v in d.iteritems()) + 1

This gives the expected output:

depth(d) # 3

Thanks to @tobias_k for suggesting simplified approach.

Notice that the function above gives 0 depth to an empty dictionary (this is why I check if d). This was useful to me in the past, but it is somewhat a convention I guess.

Answered By: FLab

Count 1 for dictionary, 0, else, and take the "worst case" of all dict-values:

my_dict = {1:{'name':'x', 'age':24, 'address':{'country':'zzz', 'zip':12345}}, 2:{'name':'y', 'age':21, 'address':{'country':'yyy', 'zip':54321}}, 3:{'name':'z', 'age':25}}

def count(d):
    return max(count(v) if isinstance(v,dict) else 0 for v in d.values()) + 1

print(count(my_dict))

I get 3

note: it only works when there are scalar & dict values. Introduce lists of nested dicts and they’re not taken into account, it would need a slightly more complex code (but still doable!)

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.