0

I'm using a nested dictionary, which contains various vertebrates types. I can currently read the nested dictionary in and search a simple sentence for a keyword (e.g., tiger).

I would like to stop the dictionary search (loop), once the first match is found.

How do I accomplish this?

Example code:

vertebrates = {'dict1':{'frog':'amphibian', 'toad':'amphibian', 'salamander':'amphibian','newt':'amphibian'},
           'dict2':{'bear':'mammal','cheetah':'mammal','fox':'mammal', 'mongoose':'mammal','tiger':'mammal'},
           'dict3': {'anteater': 'mammal', 'tiger': 'mammal'}}


sentence = 'I am a tiger'

for dictionaries, values in vertebrates.items():
for pattern, value in values.items():
    animal = re.compile(r'\b{}\b'.format(pattern), re.IGNORECASE|re.MULTILINE)
    match = re.search(animal, sentence)
    if match:
        print (value)
        print (match.group(0))
Life is complex
  • 15,374
  • 5
  • 29
  • 58

1 Answers1

1
vertebrates = {'dict1':{'frog':'amphibian', 'toad':'amphibian', 'salamander':'amphibian','newt':'amphibian'},
           'dict2':{'bear':'mammal','cheetah':'mammal','fox':'mammal', 'mongoose':'mammal','tiger':'mammal'},
           'dict3': {'anteater': 'mammal', 'tiger': 'mammal'}}


sentence = 'I am a tiger'

found = False # Initialized found flag as False (match not found)
for dictionaries, values in vertebrates.items():
    for pattern, value in values.items():
        animal = re.compile(r'\b{}\b'.format(pattern), re.IGNORECASE|re.MULTILINE)
        match = re.search(animal, sentence)
        if match is not None:
            print (value)
            print (match.group(0))
            found = True # Set found flag as True if you found a match
            break # exit the loop since match is found

    if found: # If match is found then break the loop
        break
shirish
  • 668
  • 4
  • 9