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

如何将JSON流提取的4个等长管理员属性列表组合为结构化对象

报错原因

你运行代码触发TypeError: unhashable type: 'list'的核心原因是把admin_fname、admin_sname这类列表整体当作了字典的键,Python规定只有不可变的可哈希类型(比如字符串、数字、元组)才能作为字典的key,列表属于可变类型,不符合要求。同时你的代码逻辑也和需求不符:你需要的是按「单个管理员」维度整合四个属性,而不是按属性维度聚合所有值。


解决方案

方案1:基于已有的4个等长列表实现

如果你已经生成了四个独立的等长列表,可以直接遍历zip打包后的结果,逐个生成管理员字典:

admin_list = []
# 遍历打包后的单条管理员属性
for fname, sname, admin_type, email in zip(admin_fname, admin_sname, admin_type, admin_email):
    admin_list.append({
        "firstname": fname,
        "surname": sname,
        "type": admin_type,
        "primary_email": email
    })

最终得到的admin_list是一个列表,每个元素都是对应单个管理员的结构化字典,可直接通过admin_list[索引]["属性名"]读取对应值。


方案2:更高效的最优实现(无需提前拆分4个列表)

实际上完全没必要提前把admins拆成四个独立列表,直接一次遍历就能生成目标结构,减少遍历次数,代码更简洁:

data = response.json()
admins = [item['admin_user'] for item in data['orgs']]
# 直接生成目标结构化列表
admin_list = [
    {
        "firstname": item["firstname"],
        "surname": item["surname"],
        "type": item["type"],
        "primary_email": item["primary_email"]
    } for item in admins
]

进阶:生成类实例而非字典

如果你需要的是可通过.运算符访问属性的对象,而非字典,可以用Python内置的dataclass定义结构:

from dataclasses import dataclass

# 定义管理员结构,type和内置关键字重名,这里改名为admin_type避免冲突
@dataclass
class Admin:
    firstname: str
    surname: str
    admin_type: str
    primary_email: str

data = response.json()
admins = [item['admin_user'] for item in data['orgs']]
admin_list = [
    Admin(
        firstname=item["firstname"],
        surname=item["surname"],
        admin_type=item["type"],
        primary_email=item["primary_email"]
    ) for item in admins
]

使用时直接通过admin_list[0].firstname就能读取对应属性,适合对结构规范性有要求的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:18:02