如果给定字符串与字典中的键值匹配,如何返回键

Jon*_*as 4 python dictionary

我是字典的新手,我试图找出如果给定的字符串匹配字典中的键值,如何返回键.

例:

dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}
Run Code Online (Sandbox Code Playgroud)

我想回到colorsomeothercolor,如果键的值包含blue.

有什么建议?

Moi*_*dri 7

您可以将列表理解表达式编写为:

>>> my_dict = {"color": ("red", "blue", "green"), "someothercolor": ("orange", "blue", "white")}

>>> my_color = "blue"
>>> [k for k, v in my_dict.items() if my_color in v]
['color', 'someothercolor']
Run Code Online (Sandbox Code Playgroud)

注意:不要使用dict变量,因为dictPython中是内置数据类型