我在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
可能还有多个匹配项,所以我需要人们输出多个键。在
使用这个:
你可以使用列表理解
这将打印出值与条件匹配的所有键。如果
^{pr2}$people
是字典i
是你的钥匙。这就是在字典上迭代的工作原理。不过,请记住,如果要按任何特定顺序打印键,则需要在打印前将结果保存在列表中并对其进行排序。词典不保证词条的顺序。相关问题 更多 >
编程相关推荐