【问题标题】:How to compare values of two different hash maps in python如何在python中比较两个不同哈希映射的值
【发布时间】:2018-07-06 13:30:13
【问题描述】:

您好,我想弄清楚如何比较我拥有的两个不同哈希映射的值。

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine': ['dogs','wolves']}

从上面的示例中,由于 hash2 中的键 canine 的值 'dogs' 与 hash1 中也有 'dogs' 的键动物匹配,我希望它打印出 'canine'。

当一个键只有一个值时,我能够做这样的事情,但我需要它有一个长长的值列表,如果任何值匹配,我希望它打印出它有任何匹配的键和。

编辑: 我希望它打印出'canine',因为例如,如果我在 hash2 中有多个键

hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

我只希望它打印出 'canine' 因为那是匹配的,而不是打印出整个 hash2

编辑 2: hash1 = {'动物':['狗','猫']} hash2 = {'canine': ['dogs','wolves']}

for value in hash2.values():
    if value in hash1.values():
        #not sure how to write this so here's pseudocode
        print(hash2[key of matching value])

【问题讨论】:

  • 你的问题有点不清楚。您应该提供更好的示例或更多详细信息。为什么打印出来的是“犬”而不是“动物”?你用的是什么版本的python?
  • 我使用的是 python 3.6
  • 哦,我看错了你的问题。无论是“动物”还是“犬科动物”,打印出哪一个并不重要。每当我尝试比较这些值时,我都会不断收到 KeyError。
  • 请发布您的代码
  • 为了记录,哈希映射在python中称为字典或dicts。

标签: python hashtable


【解决方案1】:

我认为这里有一些代码可以让您接近您正在寻找的内容。让我知道它是否有帮助。

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

for key, value in hash1.items():
    for key1, value1 in hash2.items():
        matches = set(value).intersection(set(value1))
        if matches:
            print(matches)
            print(key, key1)

【讨论】:

  • 请将此标记为已回答以关闭问题。
【解决方案2】:

我们可以构建一个set,其中包含来自hash1 的所有值的所有项目。然后我们可以检查该集合与hash2 的每个值之间是否有任何交集。

from itertools import chain

hash1 = {'animals':['dogs','cats']}
hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}

hash1_values = set(chain.from_iterable(hash1.values())) 
# equivalent to set(x for it in hash1.values() for x in it)


for k, v in hash2.items():
    if any(item in hash1_values for item in v):
        print(k)

【讨论】:

    【解决方案3】:

    这样的?

    for key_1,value_1 in hash1.items():
        for key_2,value_2 in hash2.items():
            if len([x for x in value_1 if x in value_2])>0:
                print(key_2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      • 2022-01-04
      • 2011-09-12
      • 1970-01-01
      相关资源
      最近更新 更多