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

6

我是初学者,想找出如何在字典中查找一个键是否与给定字符串匹配,并返回相应的键。

示例:

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

我希望在键的值包含 "blue" 时返回 "color" 和 "someothercolor"。有什么建议吗?

“red” 应该是 “红色”,同样的,“blue” 和 “green” 也应该被翻译成对应的颜色。你尝试过什么? - Rory Daulton
2
附注:不要使用 dict 作为您的字典名称,因为它是一个内置函数。请使用更具描述性的名称,如 colorscolor_dict - Billy
@RoryDaulton 我还没有尝试过值得在这里发布的任何东西。 - Jonas
你基本上是错误地使用了字典。它们是用来通过键查找值的,而不是反过来。如果你只需要做一次,下面比较昂贵的解决方案可能还可以,但如果你需要在一个大字典中运行许多这样的查找,你可能想要有第二个字典,将你要查找的值作为键,并将第一个字典中包含这些颜色的键的列表作为值。 - Klaus D.
2个回答

8

您可以将列表推导式表达为:

>>> 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
为了加速您的代码,如果可能的话,应该使用集合而不是元组。@Jonas - Denny Weinberg
1
@DennyWeinberg 对于这么小的元组,更改它所需的时间将比运行所需的额外时间大得多。 - Patrick Haugh
1
我是指输入,而不是输出。 - Denny Weinberg

1

解决方案是(不使用理解表达式)

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接