In Python, How do you loop through a list if one value is missing in that list?

Solution 1:

It appears that response2 doesn't have right key-value pair. Maybe you could try using a controlled exception.

For example:

try:
    likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])
except:
    likeCount.append(0)

Also, I would strongly suggest using snake_case instead of camelCase for naming variables. In python generally snake_case is used for functions and variables, while camelCase is reserved for classes.

Hopefully my answer helped you.

Solution 2:

It is hard to be certain, but you are likely getting the error because using ['likeCount'] assumes that index is present in the object. Here is a different write:

    if not (response2[x]['items'][0]['statistics']['likeCount']):
        likeCount.append(0) 
    else:
        likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])

so that it should work:

    likeCount.append(response2[x]['items'][0]['statistics'].get('likeCount', 0))

This utilizes the get function (which won't error if the index is not found) and sets the default value to 0.