2024-06-17 18:13:13 发布
网友
我对字典还不太熟悉,我想知道如果给定的字符串与字典中的键值匹配,如何返回键。
示例:
dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}
如果键的值包含blue,则返回color和someothercolor。
blue
color
someothercolor
有什么建议吗?
解决方法是(没有理解表达)
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中内置的数据类型
dict
解决方法是(没有理解表达)
您可以将列表理解表达式写成:
注意:不要使用} 是Python中内置的数据类型
dict
作为变量,因为^{相关问题 更多 >
编程相关推荐