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

Python如何从API返回的嵌套字典列表中提取user为None的id

实现方案

你要的提取功能可以通过双层遍历加条件判断实现,两种常用写法如下:

方法1:易读的常规循环写法

# 初始化存储结果的空列表
target_ids = []

# 遍历Series中每个值(即你提到的列表结构)
for lst in data:
    # 遍历列表内的每个字典元素
    for elem in lst:
        # 筛选user为None的元素,提取id存入结果
        if elem["user"] is None:
            target_ids.append(elem["id"])

如果担心部分元素不存在user或id字段触发报错,可以用get方法取值规避KeyError:

if elem.get("user") is None:
    target_ids.append(elem.get("id"))

方法2:简洁的列表推导式写法

target_ids = [elem["id"] for lst in data for elem in lst if elem["user"] is None]

两种写法最终得到的target_ids就是你需要的、所有user字段为None对应的id集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 19:27:06