Reputation: 127
This is my dict:
{
"queued": {"failed":{}, "undelivered":{"delivered":{}}}
}
Output should be:
Code I'm using as of now (from other stack question which is not a duplicate):
def print_depth(our_dict, i=0, target_status):
for key, value in d.items():
if isinstance(value, dict):
i+=1
print_depth(value, i, target_status)
this gets me the output:
You might also wonder what is "target_status". That is a string that should be compared to keys of dict and when found, it should return "i" which is a depth value for a given key. Thanks
Upvotes: 0
Views: 231
Reputation: 9047
d = {
"queued": {"failed":{}, "undelivered":{"delivered":{}}}
}
def print_depth(dic, i=0):
if isinstance(dic, dict):
for k in dic:
print(f'{k}-->{i}')
print_depth(dic[k], i+1)
print_depth(d)
# queued-->0
# failed-->1
# undelivered-->1
# delivered-->2
Upvotes: 2
Reputation: 781814
You're incrementing i
each time through the loop. You should only increment it once for the recursive call. Do that by passing i+1
as the argument, rather than reassigning the local variable.
def print_depth(our_dict, depth=0, target_status = ""):
for key, value in d.items():
print(f"{key} {depth}")
if isinstance(value, dict):
print_depth(value, depth+1, target_status)
You also can't have positional arguments after optional arguments, so I've added a default value to target_status
. And I added a print()
line.
Upvotes: 3