Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 523
dpd Avatar asked Feb 05 '23 14:02

dpd


2 Answers

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!)

like image 84
Jean-François Fabre Avatar answered Mar 16 '23 00:03

Jean-François Fabre


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.

like image 38
FLab Avatar answered Mar 16 '23 01:03

FLab