Selecting A Single Field From A List Of Dictionaries In Python
Solution 1:
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.
Solution 2:
Use itervalues() to check your dictionary of dictionaries.
forvalin dictionList.itervalues():
ifval['Type'] == 'Dog':
print 'Dog Found'
print val
gives:
Dog Found
{'Legs': 4, 'Type': 'Dog'}
no need to use iter
/iteritems
, simply examine the values.
Solution 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
Solution 4:
I think you're just using the wrong syntax...try this:
>>>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"
Solution 5:
Try
for i in dictionList.itervalues():
if i['Type'] == "Dog":
print"Found dog!"
The problem is that, in your example, i
is the integer key. With itervalues, you grab the value at the key (aka the dictionary you are wanting to parse).
Post a Comment for "Selecting A Single Field From A List Of Dictionaries In Python"