【问题标题】:How do I iterate over a dictionary and return the key in Python?如何遍历字典并返回 Python 中的键?
【发布时间】:2013-11-04 06:57:48
【问题描述】:

我有一个 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

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

【问题讨论】:

  • 你看到i是什么了吗?这是一把钥匙。
  • 我不只是在寻找钥匙。我需要查看链接到每个键的数据,如果与搜索条件匹配,程序将返回找到匹配项的键。

标签: python dictionary


【解决方案1】:

你可以使用列表推导

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]

【讨论】:

  • 这应该在我创建的原始 for 循环中吗?因为当我尝试这样做时,程序打印出来的只是一个空数组。输出是: [] 就是这样。
  • 没关系,我让它工作了。我忘了我注释掉了我的代码中向字典添加更多内容的部分,所以它自然会返回空数据。不过谢谢,您的解决方案对我有用!
【解决方案2】:

使用这个:

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

【讨论】:

    【解决方案3】:

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

    >>> 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】:
      for i in people:
        if people[i] == criteria:
              print i
      

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

      【讨论】:

        【解决方案5】:

        试试这个,

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

        【讨论】:

          猜你喜欢
          • 2021-11-23
          • 2015-09-27
          • 1970-01-01
          • 1970-01-01
          • 2018-01-01
          • 2014-05-04
          • 1970-01-01
          • 2014-05-15
          • 1970-01-01
          相关资源
          最近更新 更多