i have a function with nested dictionary and a specipic number(in the code that i wrote it equals 1) i need to write a recursive function that goes over the dictionary and returns only the values mapped to the keys that equals the specipic chosen number here is what i wrote
def nested_get(d, key):
res=[]
for i in d.keys():
if i == key:
res.append(d[i])
return res
if type(d[i]) is dict:
another = nested_get(d[i], key)
if another is not None:
return res another
return []
print(nested_get({1:{1:"c",2:"b"},2:"b"},1))
i need it to return ['c'] but instead it returns [{1:'c',2:'b'}]
CodePudding user response:
Your program never makes it to the if type(d[i]) is dict: because it returns in the first if statement in the first iteration of the for loop.
Check if the value stored inside the key is a dict first, and don't return until after the if statements. You don't need the return [] at the end because res will be empty if nothing was appended to it.
def nested_get(d, key):
res=[]
for i in d.keys():
if type(d[i]) is dict:
res.extend(nested_get(d[i], key))
else:
if i == key:
res.append(d[i])
return res
print(nested_get({1:{1:"c",2:"b"},2:"b"},1))
print(nested_get( {1:{1:"a",2:"b"},2:{1:{1:"c",2:"b"},2:"b"}},1))
