从python中的字典列表中选择一个字段

Joe*_*Joe 3 python dictionary for-loop list

假设我有一个字典列表,如下所示:

dictionList = {1: {'Type': 'Cat', 'Legs': 4},
               2: {'Type': 'Dog', 'Legs': 4},
               3: {'Type': 'Bird', 'Legs': 2}}
Run Code Online (Sandbox Code Playgroud)

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

 for i in dictionList:
     if dictionList(i['Type']) == "Dog":
         print "Found dog!"
Run Code Online (Sandbox Code Playgroud)

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

TypeError: 'int' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

关于如何正确地做到这一点的任何想法?

Pen*_*der 9

使用values字典的迭代器:

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

编辑:我会说,虽然你在原来的问题中要求检查Type字典中的值,这有点误导.您要求的是名为"类型" 的的内容.这可能是理解你想要什么的微妙差异,但在编程方面它是一个相当大的差异.

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

  • +1,但是一个小修改:由于OP使用Py2,`dict.items`构建一个列表 - 更好地使用`viewvalues`,或者在2.6和之前的`itervalues`中. (2认同)