Why Might Python Break Down Halfway Through A Loop? Typeerror: __getitem__
Solution 1:
TypeError: 'NoneType' object has no attribute '__getitem__'
means that you attempted to use some kind of indexing, like mylist[2]
, on None
instead of on something like a list
. This means that the internal call to that object's __getitem__
failed, because None
, which is an object of type Nonetype
, doesn't have such a method defined for it.
The problem is in x.get('title')[8:]
: the get()
method didn't find any key called 'title'
in x
, so it returned None
. However, you then try to slice it with [8:]
. If it had returned a list
or similar object it would work fine, but not so with None
.
I recommend introducing some kind of error handling:
try:
desired_value = [x.get('title')[8:] for x in desired_value]
except TypeError:
return
You will have to correct and expand this stub to make it behave in a way that's appropriate for your program. Maybe instead of a return
statement you'll need to define some kind of default desired_value
or something.
Solution 2:
x.get('title')
is returning None
.
If you want to filter the list comprehension, without repeating the query, you can build a single item list from the query result and filter it if it's None
:
desired_value = [title[8:] for x in desired_value
for title in [x.get('title')]
if title]
Post a Comment for "Why Might Python Break Down Halfway Through A Loop? Typeerror: __getitem__"