如何迭代字典并在Python中返回密钥?

时间:2013-11-04 06:57:49

标签: python dictionary

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

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

5 个答案:

答案 0 :(得分: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]

答案 1 :(得分:1)

for i in people:
  if people[i] == criteria:
        print i

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

答案 2 :(得分:1)

使用此:

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

答案 3 :(得分:1)

给出姓氏和特征的字典:

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

list comprehension很好地找到符合某些条件的所有姓氏:

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

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

>>> 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']

答案 4 :(得分:0)

试试这个,

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