Search code examples
pythondataframedictionarysubdirectorypraw

How to convert a sub-dict to a dataframe?


When I do this

subm = reddit.user.karma()
print(subm)

I get this kind of dictionary:

{Subreddit(display_name='AskReddit'): {'comment_karma': 1308, 'link_karma': 4}, Subreddit(display_name='food'): {'comment_karma': 67, 'link_karma': 72}, Subreddit(display_name='Documentaries'): {'comment_karma': 128, 'link_karma': 2}, Subreddit(display_name='explainlikeimfive'): {'comment_karma': 2, 'link_karma': 1},}

How I can convert it into DF? What ever I have tried is not working, as I always get error TypeError: 'Subreddit' object is not iterable TypeError: cannot unpack non-iterable Subreddit object

From PRAW docs:

The returned dict contains subreddits as keys. Each subreddit key contains a sub-dict that have keys for comment_karma and link_karma. The dict is sorted in descending karma order. Note: Each key of the main dict is an instance of Subreddit. It is recommended to iterate over the dict in order to retrieve the values, preferably through dict.items().


Solution

  • df = pd.DataFrame(data=subm.values(), index=(key.display_name for key in subm.keys()))
    

    You will get a DataFrame with keys of original sub-dicts as columns, and display_name of each Subreddit object as index. You can always switch index and columns of the DataFrame using .T property.