嗨,我正在尝试找出如何比较我拥有的两个不同 HashMap 的值。
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 = {'犬': ['狗','狼']}
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])
最佳答案
我们可以构建一个集合
,其中包含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)
关于python - 如何在Python中比较两个不同 HashMap 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211543/