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.