【问题标题】:selecting a single field from a list of dictionaries in python从python中的字典列表中选择单个字段
【发布时间】:2012-06-05 21:31:39
【问题描述】:

假设我有一个这样的字典列表:

dictionList = {1: {'Type': 'Cat', 'Legs': 4},
               2: {'Type': 'Dog', 'Legs': 4},
               3: {'Type': 'Bird', 'Legs': 2}}

使用 for 循环,我想遍历列表,直到我捕获一个字典,其中 Type 字段等于 "Dog"。 我最好的尝试是:

 for i in dictionList:
     if dictionList(i['Type']) == "Dog":
         print "Found dog!"

但这给我带来了以下错误:

TypeError: 'int' object has no attribute '__getitem__'

关于如何正确执行此操作的任何想法?

【问题讨论】:

  • 那不是字典列表,那是字典的字典

标签: python list dictionary for-loop


【解决方案1】:

对字典使用 values 迭代器:

for v in dictionList.values():
    if v['Type']=='Dog':
         print "Found a dog!"

编辑:我会说,尽管在您最初的问题中,您要求检查字典中某个值的Type,这有点误导。您要求的是名为“类型”的 value 的内容。这对于理解你想要什么可能是一个微妙的差异,但在编程方面却是一个相当大的差异。

在 Python 中,您应该很少需要对任何内容进行类型检查。

【讨论】:

  • +1,但有一个小的修改:由于 OP 使用的是 Py2,dict.items 构建了一个列表 - 最好使用 viewvalues,或者在 2.6 和之前的 itervalues 中使用。
【解决方案2】:

使用itervalues() 查看您的词典。

for val in dictionList.itervalues():
   if val['Type'] == 'Dog':
      print 'Dog Found'
      print val

给予:

Dog Found
{'Legs': 4, 'Type': 'Dog'}

无需使用iter/iteritems,只需检查值即可。

【讨论】:

    【解决方案3】:
    >>> diction_list = {1: {'Type': 'Cat', 'Legs': 4},
                2: {'Type': 'Dog', 'Legs': 4},
                3: {'Type': 'Bird', 'Legs': 2}}
    >>> any(d['Type'] == 'Dog' for d in diction_list.values())
    True
    

    【讨论】:

      【解决方案4】:

      我认为您只是使用了错误的语法...试试这个:

      >>> a = {1: {"Type": "Cat", "Legs": 4}, 2: {"Type": "Dog", "Legs": 4}, 3: {"Type": "Bird", "Legs": 2}}
      >>> for item in a:
      ...     if a[item].get("Type") == "Dog":
      ...             print "Got it"
      

      【讨论】:

      • 永远不要将变量声明为dict
      • get 不需要默认参数,如果你省略它就是None
      • 废话。感谢这两个修复。甚至没有考虑过 dict,忘记了 .get 的默认默认值
      【解决方案5】:

      试试

      for i in dictionList.itervalues():
          if i['Type'] == "Dog":
              print "Found dog!"
      

      问题在于,在您的示例中,i 是整数键。使用 itervalues,您可以获取键处的值(也就是您要解析的字典)。

      【讨论】:

      • 你认为dictionList(i['Type'])会做什么?
      【解决方案6】:

      尝试打印出i 的值。他们不是你认为的那样。这样做的方法是:

      for key,  val in dictionList.items():
          #do stuff to val 
      

      【讨论】:

        【解决方案7】:

        在字典中通过键访问会更好。在您的情况下,这两个字典对象都适用。

        for i in dictionList.keys():
            if dictionList[i]['Type'] == 'Dog':
                print i
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-03-17
          • 1970-01-01
          • 1970-01-01
          • 2010-11-15
          • 1970-01-01
          • 1970-01-01
          • 2017-05-05
          相关资源
          最近更新 更多