问题描述
让我说我有一个这样的字典列表: dictionList = {1:{'Type':'Cat ','Legs':4},
2:{'Type':'Dog','Legs':4},
3:{'Type':'Bird','Legs' 2}}
使用for循环我想迭代列表,直到我找到一个字典类型
字段等于狗
。
我最好的尝试是:
for d in dictionList:
如果dictionList(i ['Type' ])==狗:
打印找狗!
但是这会让我出现以下错误:
TypeError:'int'对象没有属性'__getitem__'
任何关于如何正确执行此操作的想法?
使用值
iterator for dictionaries:
for v in dictionList.values():
if v ['Type'] =='狗':
打印找到一只狗!
编辑:我会说,在你的原始问题,你要求查看键入
字典中的值,这有点误导。您要求的是名为Type的值的内容。这可能是一个微妙的区别,以了解你想要什么,但它是一个相当大的差异在程序设计。
在Python中,你应该只有RARELY需要键入 - 检查任何东西。
Lets say I have a list of dictionaries like so:
dictionList = {1: {'Type': 'Cat', 'Legs': 4},
2: {'Type': 'Dog', 'Legs': 4},
3: {'Type': 'Bird', 'Legs': 2}}
Using a for loop I want to iterate through the list until I catch a dictionary with a Type
field equal to "Dog"
.My best attempt was:
for i in dictionList:
if dictionList(i['Type']) == "Dog":
print "Found dog!"
But that gets me the following error:
TypeError: 'int' object has no attribute '__getitem__'
Any ideas on how to properly do this?
Use the values
iterator for dictionaries:
for v in dictionList.values():
if v['Type']=='Dog':
print "Found a dog!"
EDIT: I will say though that in your original question you are asking to check the Type
of a value in a dictionary, which is somewhat misleading. What you are requesting is the content of a value called 'Type'. This may be a subtle difference to understanding what you want, but it is a rather large difference in terms of programming.
In Python, you should ever only RARELY need to type-check anything.
这篇关于从python中的字典列表中选择一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!