我是词典的新手,如果给定的字符串与字典中的键值匹配,我试图找出如何返回键。
示例:
dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}
如果密钥的值包含color
,我想返回someothercolor
和blue
。
有什么建议吗?
答案 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)