Josh Alexandre
Josh Alexandre

Reputation: 127

How to test if none of the iterables are true in Python 3

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.

Upvotes: 1

Views: 253

Answers (2)

Pythonista
Pythonista

Reputation: 11635

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.

Upvotes: 4

linusg
linusg

Reputation: 6439

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!

Upvotes: 2

Related Questions