Search code examples
pythondictionarytwittertweepytwitter-api-v2

Tweepy (API V2) - Convert Response into dictionary


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


Solution

  • Found the solution! 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']