嗨,我正在尝试弄清楚如何比较我拥有的两个不同哈希映射的值。
hash1 = {'animals':['dogs','cats']}
hash2 = {'canine': ['dogs','wolves']}
在上面的示例中,由于hash2中的关键犬的值“ dogs”与也具有“ dogs”的hash1中的关键动物匹配,因此我希望它打印出“ canine”。
当一个键只有一个值时,我能够执行类似的操作,但是我需要它具有一长串值,并且如果任何值匹配,我希望它打印出具有任何匹配项的键用。
编辑: 我希望它打印出“犬齿”,因为例如,如果我在hash2中有多个键
hash2 = {'canine':['dogs','wolves'],'domestic':['horse','rabbit']}
我只希望它打印出“ canine”,因为那是匹配的,而不是打印出整个hash2
编辑2: hash1 = {'动物':['狗','猫']} hash2 = {'犬':['狗','狼']}
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])
答案 0 :(得分: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)
答案 1 :(得分:0)
我们可以构建一个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)
答案 2 :(得分:0)
像这样吗?
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)