I am trying to fetch all key,val pairs from a dictionary and my goal is to return true from the function when the key value pairs match a certain value or return false if there are no matches. I observe that on using 'return' with the recursive call, the 'for' loop navigates to the innermost loop but stops there and does not execute the remaining outer layer loop. Not sure why? As per the concepts of recursion they should. What am i missing?
Below is the code Snippet
resp = ' { "name": "Stuart", "response" : { "age" : "27", "weight" : "50"}, "address" : "New York" }'
response = json.loads(resp)
def recursive_loop(response):
for key, value in response.items():
if type(value) is dict:
return recursive_loop(value)
elif key == "address" and value == "New York":
print ("Match")
return True
else:
print (value)
return False
z = recursive_loop(response)
print (z)
The output I get:
Stuart
27
50
False
The output I expect:
Stuart
27
50
Match
True
returning? - Scott Huntertype(value) is dictevaluates to True, a return statement is hit and the remaining items you are iterating over are not run. Maybe a return here is not what you are looking for ? - TSpark