Home > Enterprise >  Tweepy (API V2) - Convert Response into dictionary
Tweepy (API V2) - Convert Response into dictionary

Time:12-01

I want to get the information about the people followed by the Twitter account "POTUS" in a dictionary. My code:

import tweepy, json

client = tweepy.Client(bearer_token=x)

id = client.get_user(username="POTUS").data.id

users = client.get_users_following(id=id, user_fields=['created_at','description','entities','id', 'location', 'name', 'pinned_tweet_id', 'profile_image_url','protected','public_metrics','url','username','verified','withheld'], expansions=['pinned_tweet_id'], max_results=13)

This query returns the type "Response", which in turn stores the type "User":

Response(data=[<User id=7563792 name=U.S. Men's National Soccer Team username=USMNT>, <User id=1352064843432472578 name=White House COVID-19 Response Team username=WHCOVIDResponse>, <User id=1351302423273472012 name=Kate Bedingfield username=WHCommsDir>, <User id=1351293685493878786 name=Susan Rice username=AmbRice46>, ..., <User id=1323730225067339784 name=The White House username=WhiteHouse>], includes={}, errors=[], meta={'result_count': 13})

I've tried ._json and .json() but both didn't work.

Does anyone have any idea how I can convert this response into a dictionary object to work with? Thanks in advance

CodePudding user response:

Found the soloution! Adding return_type=dict to the client will return everything as a dictionary!

client = tweepy.Client(bearer_token=x, return_type=dict)

However, you then have to change the line to get the User ID a bit:

id = client.get_user(username="POTUS")['data']['id']

CodePudding user response:

You can do

previous_cursor, next_cursor = None, 0

while previous_cursor != next_cursor:
    followed_data = api.get_friend_ids(username = "POTUS", cursor = next_cursor)
    previous_cursor, next_cursor = next_cursor, followed_data["next_cursor"]
    followed_ids = followed_data["id"] #this is a list
    # do something with followed_ids like writing them to a file

to get the user ids of the followed accounts.

If you want the usernames and not the ids, you can do something very similar with api.get_friends() but this returns fewer items at a time so if you plan to follow those accounts, using the ids will probably be quicker.

  • Related