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

2024-07-05 10:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

对如何正确地做这件事有什么想法吗?


Tags: in列表forif字典type错误cat
3条回答

使用itervalues()检查字典。

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

给出:

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

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

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

使用字典的values迭代器:

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

编辑:我要说的是,在你最初的问题中,你要求检查字典中某个值的Type,这有点误导。您请求的是名为“Type”的的内容。这可能是理解您想要什么的细微差别,但在编程方面却是相当大的差别。

在Python中,您应该很少需要键入check任何内容。

相关问题 更多 >