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

Python嵌套字典遍历求助:如何批量提取用户姓名与邮箱

解决嵌套字典与列表的遍历问题

错误原因

你遇到的TypeError是因为data['data']是一个列表(字典结构里的方括号[]表示列表类型),列表只能用整数索引(比如[0])或切片访问,不能直接用字符串键(比如'firstName')。

修正后的代码

直接遍历data['data']列表中的每个用户字典,提取所需字段:

import json

if response.status_code == 200:
    data = json.loads(response.text)
    # 遍历列表里的每个用户条目
    for user in data['data']:
        first_name = user['firstName']
        last_name = user['lastName']
        email = user['email']
        print(f"姓名:{first_name} {last_name},邮箱:{email}")
else:
    print(f"Error: {response.status_code}")

健壮性优化(可选)

如果返回的用户数据可能存在缺失字段的情况,建议用dict.get()方法避免KeyError:

if response.status_code == 200:
    data = json.loads(response.text)
    for user in data['data']:
        first_name = user.get('firstName', '未知名')
        last_name = user.get('lastName', '未知姓')
        email = user.get('email', '无邮箱')
        print(f"姓名:{first_name} {last_name},邮箱:{email}")
else:
    print(f"Error: {response.status_code}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:20:35