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

时间:2016-11-08 20:21:21

标签: python dictionary

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

示例:

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

如果密钥的值包含color,我想返回someothercolorblue

有什么建议吗?

2 个答案:

答案 0 :(得分:7)

您可以将 list comprehension 表达式编写为:

>>> 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用作变量,因为dict是Python中的内置数据类型

答案 1 :(得分:0)

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

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)