1

I cannot explain myself, why I cannot break out of this loop? Here is my code:

import json

doc="subtest12"

def traverse(d):

    for key, item in d.items():
        print(key)
        if doc.lower()==key.lower():
            print("YES")
            return 

        else:
            if isinstance(item, dict):
                #print(item)
                traverse(item)

d={"test":{"subtest11":"Hi","subtest12":"Hi"},"test2":{"subtest21":"Hi","subtest22":"Hi"},"test3":{"subtest31":"Hi","subtest32":"Hi"},"test4":{"subtest41":"Hi","subtest42":"Hi"}}

traverse(d)

Inside the true if condition I tried return and break. But bot does not quit the for loop...

Any idea why?

1 Answers1

0

A simple solution could be to return a value depending on if the condition is met, so that the parent function knows whether to exit or continue.

def traverse(data, stop_condition='subtest12'):
    stop_condition = stop_condition.lower()

    for k, v in data.items():
        print(k)
        if stop_condition == k.lower():
            print("YES")
            # exit directly, don't check other values in parent call
            return True

        if isinstance(v, dict):
            if traverse(v):
                # exit directly, don't check other values in parent call
                return True

    # check other values in parent call, of there are any
    return False


if __name__ == '__main__':
    d = {
        "test": {
            "subtest11": "Hi",
            "subtest12":"Hi",
        },
        "test2": {
            "subtest21": "Hi",
            "subtest22": "Hi",
        },
        "test3": {
            "subtest31": "Hi",
            "subtest32": "Hi",
        },
        "test4": {
            "subtest41": "Hi",
            "subtest42": "Hi",
        },
    }

    traverse(d)
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Another option could be to raise an exception when the condition is met, but that might be a bit confusing (an exception indicating a success state is semantically unexpected). – Ralf Aug 23 '19 at 15:22