Reputation: 181
From my standard input I take two words and I want to process them if they occur in a dictionary. This means that I can have both, one or none of the words match (in which case I will wrap up the code with an error message). This is very similar to a boolean OR gate. I can write my script like this:
if word1 in dict and word2 in dict:
# process word1
# process word2
elif word1 in dict:
# process word1
elif word2 in dict:
# process word2
else:
# error msg
However, this seems rather redundant. Is there a simple alternative to this? I have a separate function that processes one of these words at a time.
Upvotes: 2
Views: 88
Reputation: 2387
Now that it's clear that processing of both words is nothing special, i.e. just sequential processing of the individual words, you can reduce your code by moving up the error check to the top:
if word1 not in dict and word2 not in dict:
# raise Exception or print and return
if word1 in dict:
# process word1
if word2 in dict:
# process word2
Readable and no extra state variables needed.
Upvotes: 1
Reputation: 51653
You can leverage all(..)
to check if multiple keys are in your dictionary - this will test all things until a False one is found or all are True:
def doSmthWithAllOfThem(words,dictionary):
print(words, "are in it")
print(sum(dictionary[word] for word in words) )
d = {"w{}".format(i):i for i in range(10)}
words = {"w1","w9","w4"}
if all(w in d for w in words):
doSmthWithAllOfThem(words,d)
elif "w9" in dict:
pass
else:
raise ValueError("not in")
Output:
{'w4', 'w9', 'w1'} are in it
14
You could also use set
-intersection operation:
words = {"w1","w9","w4"}
if words & set(d.keys()) == words:
doSmthWithAllOfThem(words,d)
or (cudos to @jpp) the use set
-issubset operation:
if words <= set(d.keys()):
doSmthWithAllOfThem(words,d)
(Output in both set-usage
cases identical to the one above)
The intersection returns only things that are in both sets - if the result afterwards is euqal to words
all elements were in your dict.
Upvotes: 0
Reputation: 13539
If processing word1 and word2 is independent of each other, then you can modify your code as follows:
word_found = False
if word1 in dict:
#process word1
word_found = True
if word2 in dict:
#process word2
word_found = True
if not word_found:
#error message
Upvotes: 1