How to return key if a given string matches the keys value in a dictionary
本问题已经有最佳答案,请猛点这里访问。
我对字典不太熟悉,我正在尝试找出如果给定的字符串与字典中的键值匹配,如何返回键。
例子:
1 | dict = {"color": (red, blue, green),"someothercolor": (orange, blue, white)} |
如果键的值包含
有什么建议吗?
您可以将列表理解表达式写成:
1 2 3 4 5 | >>> 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'] |
注意:不要使用
解决方法是(没有理解的表达)
1 2 3 4 5 6 | 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) |
号