我有一个 Python 字典,以人们的姓氏为键,每个键都有多个链接到它的值。有没有一种方法可以使用 for 循环遍历字典来搜索特定值,然后返回该值链接到的键?
for i in people:
if people[i] == criteria: #people is the dictionary and criteria is just a string
print dictKey #dictKey is just whatever the key is that the criteria matched element is linked to
可能还有多个匹配项,所以我需要人们输出多个键。
请您参考如下方法:
你可以使用列表理解
print [key
for people in peoples
for key, value in people.items()
if value == criteria]
这将打印出值符合条件的所有键。如果 people 是字典,
print [key
for key, value in people.items()
if value == criteria]
