1
votes

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
3
What "concept of recursion" do you believe should allow a function to resume after returning? - Scott Hunter
@ScottHunter, I get your point but is there a way I don't return False until the entire execution is complete. I believe even if I don't explicitly use the "Return False" statement at the end of the function, python by default would return None stopping the execution. - Rakesh Agarwal
I believe you are seeing this behaviour because you are using both iteration and recursion. What is happening is as soon as type(value) is dict evaluates 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

3 Answers

0
votes

return stops the execution of the function, regardless of recursion or it being in a loop, such that it can't be resumed.

You might want to look into yield.

0
votes

You only want to return early from the loop if the recursion returns True. Other wise you want to continue with the loop and examine the rest of the values in case one of these meets your condition. To do this with minimal change, just add a condition to test the result of the recursive call.

def recursive_loop(response):
    for key, value in response.items():
        if type(value) is dict:
            if recursive_loop(value):
                return True
        elif key == "address" and value == "New York":
            return True
    return False

This will cause a depth-first search and return when it first discovers a true condition.

-2
votes

the return function is the problem. Try with yield