Reputation: 8847
Could someone with superior python skills please explain why am I getting a "bool is not iterable" error, when I am only doing some dict lookups and comparisons?
This is the last line of the stack trace:
---> 54 if 'identifiers' in document and 'doi' in document['identifiers'] and document['identifiers']['doi'] == row['doi']:
55 print 'Found DOI'
56 return True
TypeError: ("argument of type 'bool' is not iterable", u'occurred at index 2914')
Is best practice to use a try/except
to attempt to read my dict and catch if the key does not exist?
Upvotes: 2
Views: 8436
Reputation: 11347
When an object doesn't provide contains()
, in
attempts to iterate it (https://docs.python.org/2/reference/expressions.html#membership-test-details)
>>> print 1 in True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
>>>
The problem seems to be that the key does exist, but has the wrong type, so the in
check isn't helpful here. Generally, in python it's better to follow EAFP and handle an exception instead of trying to pre-check everything.
Upvotes: 9
Reputation: 873
document['identifiers'] is a bool type, and the 'in' is trying to iterate over a bool variable which is giving you this error.
Upvotes: 1
Reputation: 6221
I don't think this is the cause of your error, but you can use the get method:
dict.get(key, default=None)
You can define an optional default value to return if the key is not present, and it won't trip an error.
Upvotes: -1