如何将子字典转换为数据框?

How to convert a sub-dict to a dataframe?

当我这样做时

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

我得到了这种字典:

{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},}

如何将其转换为 DF? 我尝试过的方法都不起作用,因为我总是收到错误 TypeError: 'Subreddit' object is not iterable TypeError: cannot unpack non-iterable Subreddit object

来自 PRAW 文档:

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().

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

你将得到一个 DataFrame,其中原始子字典的键作为列,每个 Subreddit 对象的 display_name 作为索引。 您始终可以使用 .T 属性.

切换 DataFrame 的索引和列