【问题标题】:Print the key using the value of a dictionary使用字典的值打印键
【发布时间】:2020-04-19 08:21:13
【问题描述】:

我有一个矩阵 a=[0, 4, 8] 以及查找字典中的哪些键 d = {"a":0, "b":1, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10} 具有矩阵 a 中的值。

我有以下代码:

for i in a:
    [key for key, value in d.items() if value == i]
    print(key)

但是,在运行此代码时,我收到以下消息:

ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()。

我尝试在数组后面添加 .any() 和 .all(),但它不起作用。

有谁知道我该如何解决这个问题?

【问题讨论】:

  • 显示a 的示例,我们可以在其中重新创建您遇到的错误。 a 是可迭代的吗?
  • 您没有在任何地方分配列表理解。您可能想要附加到列表中。 key 也没有在任何地方定义,它只存在于 list-comp 内的本地 namespace 中,因此无法从外部访问
  • 你声明字典的方式不对。

标签: python python-3.x dictionary keras key


【解决方案1】:

可能最简单:

for k, v in d.items():
    if v in a:
        print(k)

【讨论】:

    【解决方案2】:

    您可以像这样重新格式化您的代码:

    a = [0, 4, 8]
    d = {"a":0, "b":1, "c":3, "d":4, "e":5, "f":6, "g":7, "h":8, "i":9, "j":10}
    
    keys = [key for key in d.keys()if d[key] in a ]
    print(keys)
    # Output ['a', 'd', 'h']
    

    【讨论】:

      【解决方案3】:

      您可以通过索引方法获取给定valuekey

      代码

      a=[0, 4, 8]   #matrix a
      d = {'a':0, 'b':1, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':1}   #dictionary d
      
      values = list(d.values())  #generating values list
      keys = list(d.keys())    #generating keys list
      for i in a:      #iterating over the elements of matrix or list a
          if i in values:    #chck whether the value in the dictionary
              print("Key for",i,"is",keys[values.index(i)])    #displaying result
      

      输出:

      Key for 0 is a
      Key for 4 is d
      Key for 8 is h
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 2021-08-14
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        • 2023-03-23
        • 1970-01-01
        • 2017-03-19
        • 1970-01-01
        • 2018-05-16
        相关资源
        最近更新 更多