我是初学者,想找出如何在字典中查找一个键是否与给定字符串匹配,并返回相应的键。
示例:
dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}
我希望在键的值包含 "blue" 时返回 "color" 和 "someothercolor"。有什么建议吗?
我是初学者,想找出如何在字典中查找一个键是否与给定字符串匹配,并返回相应的键。
示例:
dict = {"color": (red, blue, green), "someothercolor": (orange, blue, white)}
您可以将列表推导式表达为:
>>> 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中的内置数据类型。解决方案是(不使用理解表达式)
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)
dict
作为您的字典名称,因为它是一个内置函数。请使用更具描述性的名称,如colors
或color_dict
。 - Billy