检查字符串的任何键中是否出现字符串

jat*_*h03 0 python dictionary

我正在尝试检查字符串是否字典的其中一个键中.

if message in a_dict: # this will only work if message is exactly one of the keys
    #do stuff
Run Code Online (Sandbox Code Playgroud)

我希望条件返回,True即使message它只是其中一个a_dict键的一部分.

我该怎么办?有没有办法.*在字符串中添加正则表达式?或者,还有更好的方法?

Dan*_*iel 9

你可以使用any:

elif any(message in key for key in a_dict):
    do_something()
Run Code Online (Sandbox Code Playgroud)

如果您还需要包含消息的密钥:

else:
    key = next((message in key for key in a_dict), None)
    if key is not None:
        do_something(key)
Run Code Online (Sandbox Code Playgroud)