Reputation: 2359
I'm trying to check if a string is in one of the keys of a dictionary.
if message in a_dict: # this will only work if message is exactly one of the keys
#do stuff
I want the condition to return True
even if message
is only part of one of a_dict
's keys.
How would I do that? Is there a way to add a regex .*
in the string? Or is there a better way?
Upvotes: 7
Views: 8505
Reputation: 42758
You can use any
:
elif any(message in key for key in a_dict):
do_something()
If you need also the key which contains the message:
else:
key = next((message in key for key in a_dict), None)
if key is not None:
do_something(key)
Upvotes: 12
Reputation: 8781
You can't really do what you want with Python's in
operator. It's best to do the check by hand - iterate over all the keys and see if any of them contains your message
.
Upvotes: 0