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.
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!)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With