I am trying to get the old age level of a person from this dictionary:
d = {'Sıdıka': [{'Aziz': [{'Ahmet': [{'Kuzey': []}]}, {'Öznur': [{'Elif': []}, {'Yiğit': []}]}, {'İlknur': [{'Nurullah': []}, {'Büşra': []}]}, {'İlker': [{'Melih': []}]}]}]}
"Sıdıka" is the eldest one and I want to determine her level (which is 3 (Ex. "Sıdıka" is "Kuzey"'s father's, father's, mother. Which makes 3)).
How can i achieve that?
I tried: Recursion, but couldn't figure it out how.
My attempt:
def new(self,dict,count,max):
for i in dict:
print(dict[i])
if len(dict[i])!=0:
for i in dict[i]:
self.new(self,i,count,max)
count+=1
print(count)
else:
return count
Here is a simple recursion in one statement (assuming d
the input dictionary).
You can uncomment the print to see how it works.
def level(d, lvl=0):
#print(f'level {lvl}:', d)
return max((lvl, *(level(l, lvl=lvl+1)
for v in d.values()
for l in v)
))
level(d)
Output: 3