You need to enable JavaScript to run this app. Python字典推导式提取Tweet嵌套JSON深层键值对实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Python字典推导式提取Tweet嵌套JSON深层键值对实现方法

嵌套JSON统一提取的实现方法

原有写法的核心问题

你之前尝试的写法存在本质偏差:放进可迭代集合里的tweets[i]._json['user']['geo_enabled']是字段对应的实际取值,而非从哪个路径取值的路径标识。字典推导遍历集合时,会尝试把这个返回值当作一级键去原JSON里匹配,自然无法正常运行。
如果要在同一套逻辑里同时提取一级键、深层嵌套键,核心思路是把所有字段的提取规则(输出的键名、取值的查找路径)做统一配置,不用区分一级和深层路径的差异。

具体实现步骤

  • 实现通用取值函数
    写一个顺着路径逐层查找字典值的通用函数,替代硬编码的多层索引取值,同时兼容路径不存在的异常场景:
    def get_nested_value(source: dict, path: list, default=None):
        current_level = source
        for key in path:
            # 遇到非字典结构、缺失键时直接返回默认值,避免抛KeyError中断流程
            if not isinstance(current_level, dict) or key not in current_level:
                return default
            current_level = current_level[key]
        return current_level
    
  • 统一配置所有要提取的字段
    不管是一级键还是深层嵌套键,都用(最终输出键名, 查找路径)的结构做配置,路径从JSON根层级开始逐层写就行:
    extract_rule = [
        # 一级字段,路径就是单层键名
        ("created_at", ["created_at"]),
        ("id", ["id"]),
        ("full_text", ["full_text"]),
        # 深层字段,路径逐层写,最终输出的键名可以和原JSON保持一致,也可以自定义
        ("geo_enabled", ["user", "geo_enabled"])
    ]
    
  • 生成目标提取结果
    用字典推导统一遍历规则生成selected字典,不用单独给深层字段写硬编码取值:
    selected = {
        out_key: get_nested_value(tweets[i]._json, look_up_path)
        for out_key, look_up_path in extract_rule
    }
    

简化优化方案

如果觉得列表写路径太繁琐,可以用点分隔的字符串表示深层路径,比如把["user", "geo_enabled"]简化成"user.geo_enabled",只需要把取值函数稍微调整下:

def get_value_by_dot_path(source: dict, dot_path: str, default=None):
    current_level = source
    for key in dot_path.split('.'):
        if not isinstance(current_level, dict) or key not in current_level:
            return default
        current_level = current_level[key]
    return current_level

对应的配置就可以简化成字典映射,整体写起来更轻便:

dot_path_rule = {
    "created_at": "created_at",
    "id": "id",
    "full_text": "full_text",
    "geo_enabled": "user.geo_enabled"
}
selected = {
    out_key: get_value_by_dot_path(tweets[i]._json, path_str)
    for out_key, path_str in dot_path_rule.items()
}

这种方式相比直接硬编码多层索引的优势:可以统一处理字段缺失的场景,不会因为某条推文的嵌套结构缺键(比如缺失user字段、缺失geo_enabled字段)就直接报错,能平滑返回预设的默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 04:54:04