Search code examples
pythonfor-looptwitteriterable

TypeError: 'int' object is not iterable on Python Twitter API


I am extracting text, screen_name, hashtags, follower counts, etc from tweets using Twitter library.

I have no problems getting screen_name, hashtags, and text because they are all strings.

How can I extract follower counts which is 'int' object and save into the format of list?

status_texts = [status['text']
                for status in statuses]
screen_names = [user_mention['screen_name']
                for status in statuses
                    for user_mention in status['entities']['user_mentions']]
followers = [user['followers_count']
            for status in statuses
                for user in status['user']['followers_count']]

Result of first two codes are

["RT @ESPNStatsInfo: Seven of the NBA's top 10 all-time leading scorers never had back-to-back 50-point games. \n\nKareem Abdul-Jabbar\nKarl Mal…", 'RT @kirkgoldsberry: The game has changed. Rookie LeBron versus Doncic"]
['ESPNStatsInfo', 'kirkgoldsberry', 'ESPNStatsInfo', 'warriors', 'MT_Prxphet', 'Verzilix', 'BleacherReport']

My expected result is

[10930,13213,15322,8795,9328,23519]

But when I try to extract the number of followers and save them into the format of list, it returns TypeError: 'int' object is not iterable. I know I am getting this error because result of follower_counts is in integer and I can't use for with integer.

In this case, do I need to convert int into str ? or do I need to use range ?

I know using tweepy is much easier way but I want to use twitter first


Solution

  • So I expect the dictionnary representating the json response from your API call to be called jsonResponse.

    This way, you already know that you can get every tweet by doing statuses = jsonResponse['statuses']. (I'm expecting your statuses to be that too.)

    From there,i'm guessing that you want a list of amount of followers for each tweets. So for status in statuses, you want the followers count. Which , in python, looks simply like this :

    followers_counts = [status['user']['followers_count'] for status in statuses]
    

    An other way is to map the statuses list :

    followers_count = map(lambda status: status['user']['followers_count'], statuses)
    

    With map you can even more simply make a dictionnary of the infos you want for each tweet. But that would just look like the json you already get from the API.