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

2024-06-17 18:13:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我对字典还不太熟悉,我想知道如果给定的字符串与字典中的键值匹配,如何返回键。

示例:

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

如果键的值包含blue,则返回colorsomeothercolor

有什么建议吗?


Tags: 字符串示例字典greenbluered建议dict
2条回答

解决方法是(没有理解表达)

my_dict = {"color": ("red", "blue", "green"), "someothercolor": ("orange", "blue", "white")}
solutions = []
my_color = 'blue'
for key, value in my_dict.items():
    if my_color in value:
        solutions.append(key)

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

>>> 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']

注意:不要使用dict作为变量,因为^{}是Python中内置的数据类型

相关问题 更多 >