Home > Back-end >  Convert Multiple Python Dictionaries to Pandas DataFrame
Convert Multiple Python Dictionaries to Pandas DataFrame

Time:08-26

I have the following code which retrieves account info for tik tok users who have posted videos with specific hashtags.

The code returns multiple dictionaries which I would like to parse into a pandas dataframe with the dictionary keys as the column headers.

from TikTokApi import TikTokApi

hashtag = "ugc"
count=10

with TikTokApi() as api:
tag = api.hashtag(name=hashtag)

print(tag.info())

    for video in tag.videos(count=count):
       print(video.author.as_dict)

The resulting dictionaries looks something like this:

{'id': '6933', 'uniqueId': 'casiusmonet', 'nickname': 'CasiusMonet'}
{'id': '7106', 'uniqueId': 'oneoffryan', 'nickname': 'TikTok Grw'}
{'id': '7113', 'uniqueId': 'shanmy_c', 'nickname': 'Amy Shan'}
{'id': '6787', 'uniqueId': 'mayaelesse', 'nickname': 'maya'}...

Desired pandas dataframe result:

id uniqueId nickname
6933 casiusmonet CasiusMonet
7106 oneoffryan TikTok Grw
7113 shanmy_c Amy Shan
6787 mayaelesse maya

How can I achieve the above result?

thanks.

CodePudding user response:

Just collect the dictionaries into a list and create a DataFrame:

lst = []
for video in tag.videos(count=count):
   lst.append(video.author.as_dict)

df = pd.DataFrame(lst)
print(df)
  • Related