You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套字典解析为Pandas DataFrame?及Reddit数据存储优化建议

问题描述

我编写了如下代码,用于从Reddit的tennis子版块获取帖子和评论:

headlines = {}
comments = []
i = 1
for submission in reddit.subreddit('tennis').search("Djokovic loves", sort="relevance", limit=10):
    h = {}
    c = {}
    h['title'] = submission.title
    h['id'] = submission.id
    h['score'] = submission.score
    submission.comments.replace_more(limit=0)
    for comment in submission.comments.list():
        c['author'] = comment.author
        c['body'] = comment.body
        comments.append(c)
    headlines['headline ' + str(i)] = h
    headlines['comments ' + str(i)] = comments
    i += 1

代码输出的嵌套字典结构示例如下:

{'headline 1': 
    {
        'title': 'abc', 
        'id': 123, 
        'score': 0.5
    }, 
    'comments 1': [{'author': 'James', 'body': 'He is good!'}]
}

请问能否将该嵌套字典结构解析为Pandas DataFrame?或者是否有更合适的数据结构来存储帖子与评论?

解决方案

一、将现有嵌套字典转为DataFrame

现有结构可以转成DataFrame,考虑到帖子和评论是一对多的关系,有两种常用处理方式:

方式1:拆分帖子表与评论表

这种方式符合关系型数据逻辑,方便后续单独分析帖子或评论:

import pandas as pd

posts_data = []
comments_data = []

# 遍历字典提取数据并关联帖子ID
for key, value in headlines.items():
    if key.startswith('headline'):
        posts_data.append(value)
    elif key.startswith('comments'):
        # 通过键名中的数字匹配对应帖子ID
        post_num = key.split(' ')[1]
        target_post_id = headlines[f'headline {post_num}']['id']
        # 给每条评论添加关联的帖子ID
        for comment in value:
            comment_copy = comment.copy()
            comment_copy['post_id'] = target_post_id
            comments_data.append(comment_copy)

# 生成两个独立的DataFrame
posts_df = pd.DataFrame(posts_data)
comments_df = pd.DataFrame(comments_data)

方式2:将评论嵌套在DataFrame单元格中

如果需要把单条帖子的所有评论放在同一行展示,可采用这种方式:

import pandas as pd

combined_data = []
total_posts = len(headlines) // 2

for i in range(1, total_posts + 1):
    post_info = headlines[f'headline {i}'].copy()
    post_info['comments'] = headlines[f'comments {i}']
    combined_data.append(post_info)

combined_df = pd.DataFrame(combined_data)

这种方式适合快速查看单条帖子的评论集合,但不利于对评论做批量分析。

二、更合适的数据存储方式

你当前的代码存在逻辑问题:全局的comments列表会不断累积所有帖子的评论,导致后续的comments i包含之前所有帖子的内容。建议直接构建帖子与对应评论绑定的列表结构,更清晰且便于后续处理:

优化后的采集代码

posts_with_comments = []
for submission in reddit.subreddit('tennis').search("Djokovic loves", sort="relevance", limit=10):
    post_info = {
        'title': submission.title,
        'id': submission.id,
        'score': submission.score,
        'comments': []
    }
    submission.comments.replace_more(limit=0)
    for comment in submission.comments.list():
        # 将author转为字符串,避免存储Reddit对象导致的序列化问题
        post_info['comments'].append({
            'author': str(comment.author),
            'body': comment.body
        })
    posts_with_comments.append(post_info)

这个结构中每个帖子字典仅包含自身的评论,后续转DataFrame或存储都更灵活:

  • 直接用pd.DataFrame(posts_with_comments)就能生成带嵌套评论列的DataFrame;
  • 拆分帖子和评论表也只需遍历列表提取对应字段即可。

长期存储的可选方案

如果需要持久化存储数据,还可以选择:

  • CSV/Excel:拆分帖子和评论为两个文件,用post_id作为关联字段;
  • SQL数据库(SQLite/MySQL):建立posts和comments两张表,通过外键关联,适合大规模数据的查询和管理;
  • JSON文件:直接保存posts_with_comments列表,完整保留嵌套结构,适合快速读写。

内容的提问来源于stack exchange,提问作者TheUnknownChop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:05:22