1

我在 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

可能还有多个匹配项,所以我需要人们输出多个键。

4

5 回答 5

4

您可以使用列表理解

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]
于 2013-11-04T06:59:36.477 回答
2

用这个:

for key, val in people.items():
    if val == criteria:
        print key
于 2013-11-04T07:05:51.553 回答
2

给定一个姓氏和特征的字典:

>>> people = {
    'jones': ['fast', 'smart'],
    'smith': ['slow', 'dumb'],
    'davis': ['slow', 'smart'],
}

列表推导很好地找到符合某些条件的所有姓氏:

>>> criteria = 'slow'
>>> [lastname for (lastname, traits) in people.items() if criteria in traits]
['davis', 'smith']

但是,如果您要进行许多此类查找,则构建一个将特征映射到匹配姓氏列表的反向字典会更快:

>>> traits = {}
>>> for lastname, traitlist in people.items():
        for trait in traitlist:
            traits.setdefault(trait, []).append(lastname)

现在,可以快速优雅地完成条件搜索:

>>> traits['slow']
['davis', 'smith']
>>> traits['fast']
['jones']
>>> traits['smart']
['jones', 'davis']
>>> traits['dumb']
['smith']
于 2013-11-04T07:34:15.400 回答
1
for i in people:
  if people[i] == criteria:
        print i

i是你的钥匙。这就是迭代字典的工作原理。但是请记住,如果您想以任何特定顺序打印键 - 您需要将结果保存在列表中并在打印之前对其进行排序。字典不会以任何保证的顺序保存它们的条目。

于 2013-11-04T06:59:25.367 回答
0

试试这个,

for key,value in people.items():
        if value == 'criteria':
                print key
于 2013-11-04T10:39:00.023 回答