Home > Back-end >  In Python, How do you loop through a list if one value is missing in that list?
In Python, How do you loop through a list if one value is missing in that list?

Time:01-21

My goal is to create a dataframe based on the 'viewCount', 'likeCount', 'favoriteCount' and 'commentCount'.

The code below works gives 25 values for 'viewCount', 'favoriteCount', and 'commentCount', but I get an error for 'likeCount' because 'likeCount' has 1 missing value in its list.

How can I create an "if, then statement" that will place a 0 count into the 'likeCount' list when the programs see's that value doesn't exist.

The if then statement below is what I've tried, but I'm getting a KeyError: 'likeCount' error

x=0
y=0
viewCount = []
likeCount = []
favoriteCount = []
commentCount = []

while (x < len(response2)):
    viewCount.append(response2[x]['items'][0]['statistics']['viewCount'])
    favoriteCount.append(response2[x]['items'][0]['statistics']['favoriteCount'])
    commentCount.append(response2[x]['items'][0]['statistics']['commentCount'])
    if not (response2[x]['items'][0]['statistics']['likeCount']):
        likeCount.append(0) 
    else:
        likeCount.append(response2[x]['items'][0]['statistics']['likeCount'])
    x=x 1
    
            
#print(video_title, video_id)
df2 = pd.DataFrame({'viewCount': viewCount,'favoriteCount': favoriteCount,
            'commentCount': commentCount, 'likeCount' : likeCount} )
df2

ERROR MESSAGE:

KeyError                                  Traceback (most recent call last)

     10     favoriteCount.append(response2[x]['items'][0]['statistics']['favoriteCount'])
     11     commentCount.append(response2[x]['items'][0]['statistics']['commentCount'])
---> 12     if not (response2[x]['items'][0]['statistics']['likeCount']):
     13         likeCount.append(0)
     14     else:

KeyError: 'likeCount'

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related