Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string appears in any of the keys of a dictionary

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?

like image 647
jath03 Avatar asked Dec 10 '22 13:12

jath03


1 Answers

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)
like image 152
Daniel Avatar answered Apr 13 '23 01:04

Daniel