【发布时间】: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。