【问题标题】:How to return key if a given string matches the keys value in a dictionary [duplicate]如果给定字符串与字典中的键值匹配,如何返回键[重复]
【发布时间】:2017-03-22 14:22:24
【问题描述】:

我是字典新手,我正在尝试找出如果给定字符串与字典中的键值匹配时如何返回键。

例子:

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

如果键的值包含blue,我想返回colorsomeothercolor

有什么建议吗?

【问题讨论】:

  • red 是否应该是 "red"bluegreen 也是如此?你尝试过什么?
  • 旁注:不要使用dict 作为您的字典名称,因为它是builtin。使用更具描述性的内容,例如 colorscolor_dict
  • @RoryDaulton 我还没有真正尝试过任何值得在这里发布的内容。
  • 你基本上用错了字典。它们是通过键来查找值的,而不是相反。如果你只需要做一次,下面相当昂贵的解决方案可能还可以,但是如果你必须在一个大字典中运行许多这些查找,你可能想要第二个字典,其中包含你正在寻找的值键和第一个字典中包含这些颜色作为值的键列表。

标签: python dictionary


【解决方案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)

【讨论】:

    【解决方案2】:

    你可以将列表理解表达式写成:

    >>> 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内置的数据类型

    【讨论】:

    • 为了加速你的代码你应该尽可能使用集合而不是元组。 @乔纳斯
    • @DennyWeinberg 对于这么小的元组,更改它所需的时间将比运行所需的额外时间大几个数量级。
    • 我的意思是输入,而不是输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多