[英]How do I iterate over a dictionary and return the key in Python?
I have a dictionary in Python with people's last names as the key and each key has multiple values linked to it. 我有一个用人的姓氏作为键的Python字典,每个键都有多个链接到它的值。 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循环遍历字典以搜索特定值,然后返回该值链接到的键?
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. 也许还有多个匹配项,所以我需要人们输出多个键。
You can use list comprehension 您可以使用列表理解
print [key
for people in peoples
for key, value in people.items()
if value == criteria]
This will print out all the keys for which the value matches the criteria. 这将打印出所有与值匹配的键。 If
people
is the dictionary, 如果
people
是字典,
print [key
for key, value in people.items()
if value == criteria]
for i in people:
if people[i] == criteria:
print i
i
is your key. i
是你的钥匙。 That's how iterating over dictionary works. 这就是对字典进行迭代的方式。 Remember, though, that if you want to print keys in any specific order - you need to keep results in a list and sort it before printing.
但是请记住,如果要按任何特定顺序打印密钥,则需要将结果保存在列表中并在打印之前对其进行排序。 Dictionaries don't keep their entries in any guaranteed order.
字典不会以任何保证的顺序保留其条目。
Use this: 用这个:
for key, val in people.items():
if val == criteria:
print key
Given a dictionary of lastnames and traits: 给定一个姓氏和特征词典:
>>> people = {
'jones': ['fast', 'smart'],
'smith': ['slow', 'dumb'],
'davis': ['slow', 'smart'],
}
A list comprehension nicely finds all lastnames matching some criteria: 列表理解很好地找到了符合某些条件的所有姓氏:
>>> criteria = 'slow'
>>> [lastname for (lastname, traits) in people.items() if criteria in traits]
['davis', 'smith']
However, if you're going to do many such lookups, it would be faster to build a reverse dictionary that maps traits to a list of matching last names: 但是,如果要进行许多此类查找,则构建反向字典以将特征映射到匹配的姓氏列表会更快一些:
>>> traits = {}
>>> for lastname, traitlist in people.items():
for trait in traitlist:
traits.setdefault(trait, []).append(lastname)
Now, the criteria searches can be done quickly and elegantly: 现在,可以快速而优雅地完成条件搜索:
>>> traits['slow']
['davis', 'smith']
>>> traits['fast']
['jones']
>>> traits['smart']
['jones', 'davis']
>>> traits['dumb']
['smith']
Try this one, 试试这个
for key,value in people.items():
if value == 'criteria':
print key
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.