在Python中如何遍历字典并返回键?

2024-04-28 07:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: andthe方法inforstringdictionaryif
3条回答

使用这个:

for key, val in people.items():
    if val == criteria:
        print key

你可以使用列表理解

print [key
          for people in peoples
          for key, value in people.items()
          if value == criteria]

这将打印出值与条件匹配的所有键。如果people是字典

^{pr2}$
for i in people:
  if people[i] == criteria:
        print i

i是你的钥匙。这就是在字典上迭代的工作原理。不过,请记住,如果要按任何特定顺序打印键,则需要在打印前将结果保存在列表中并对其进行排序。词典不保证词条的顺序。

相关问题 更多 >