1

The task is to take an inputted string (query) and see if any of the words match the keys in a dictionary (rsp_dict). Simple.

words = query.split()

for each in words:
    if each in rsp_dict:
        print(rsp_dict[each])

But what I can't figure out, is how to make it print out a phrase if none of the words match keys from the dictionary. I've tried a million different methods, but I always end up with the phrase printing for every False value, rather than just the once.

I'm really hoping to learn from this so any help or guidance is really appreciated. Please also feel free to suggest edits on how I've phrased this question.

Braiam
  • 1
  • 11
  • 47
  • 78
Josh Alexandre
  • 127
  • 3
  • 3
  • 11

2 Answers2

4

Assuming words = input(*) here

Using sets:

not set(words.split()).isdisjoint(rsp_dict.keys())

Using any:

any(w in words.split() for w in rsp_dict.keys())

Using a list comprehension:

[w for w in words.split() if w in rsp_dict.keys()]

Using any of these:

if (expression):
   print("Found a matching word in phrase")
else:
   print("No matches")

Less fancy, but you can always use your regular run of the mill forloop.

Pythonista
  • 11,377
  • 2
  • 31
  • 50
2

You can do it like this:

words = query.split()
not_found = True

for each in words:
    if each in rsp_dict:
        print(rsp_dict[each])
        not_found = False

if not_found:
    print("The phrase was not found!")

Hope this helps!

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
linusg
  • 6,289
  • 4
  • 28
  • 78
  • @Tamas Hegedus Thanks for the edit, was a thinking mistake ;) – linusg Apr 21 '16 at 20:41
  • 1
    Neat, simple solution! Really appreciate the help, thank you! I also added a 'break' below the 'not_found = False' for when queries that contained two words matching keys. – Josh Alexandre Apr 22 '16 at 05:27