Skip to content Skip to sidebar Skip to footer

Why Might Python Break Down Halfway Through A Loop? Typeerror: __getitem__

The Goal I have a directory with 65 .txt files, which I am parsing, one by one, and saving the outputs into 65 corresponding .txt files. I then plan to concatenate them, but I'm no

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__"