如何遍历字典并在Python中返回键? [英] How do I iterate over a dictionary and return the key in Python?
本文介绍了如何遍历字典并在Python中返回键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Python中有一本字典,其中以人们的姓氏为键,每个键都有多个与之链接的值.有没有一种方法可以使用for循环遍历字典以搜索特定值,然后返回该值链接到的键?
I have a dictionary in Python with people's last names as the key and each key has multiple values linked to it. Is there a way to iterate over the dictionary using a for loop to search for a specific value and then return the key that the value is linked to?
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
也许还有多个匹配项,所以我需要人们输出多个键.
There maybe multiple matches as well so I need to people to output multiple keys.
推荐答案
您可以使用列表理解
print [key
for people in peoples
for key, value in people.items()
if value == criteria]
这将打印出所有值与条件匹配的键.如果people
是词典,则
This will print out all the keys for which the value matches the criteria. If people
is the dictionary,
print [key
for key, value in people.items()
if value == criteria]
这篇关于如何遍历字典并在Python中返回键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文