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

如何将dataclass对象列表中的指定字段导出为字典?

解决方法

一、简便转换指定字段为字典

不需要手动遍历构建,用Python的字典推导式就能简洁实现,这是最常用且高效的方式:

示例1:以id为键,name为值

id_to_name = {p.id: p.name for p in players}
print(id_to_name)

输出:

{123: 'Alice', 456: 'Bob', 789: 'Gemma'}

示例2:以name为键,id为值

name_to_id = {p.name: p.id for p in players}

示例3:以name为键,color为值

name_to_color = {p.name: p.color for p in players}

字典推导式是遍历逻辑的简化写法,比手动初始化字典再逐个添加更简洁,性能和直接遍历一致。

二、处理重复键:保留首次出现的键值对

常规字典推导式会保留最后一次出现的键值对(后出现的会覆盖前面的)。要保留首次出现的,有两种简便方式:

方式1:借助dict.fromkeys() + 遍历填充

dict.fromkeys()会自动忽略后续重复的键,只保留第一个遇到的键,之后再遍历填充对应的值:

# 模拟含重复name的列表
players_with_dup = [
    Player(123, "Alice", "green"),
    Player(456, "Bob", "red"),
    Player(789, "Alice", "blue"),  # 重复name
]

name_to_id_first = dict.fromkeys((p.name for p in players_with_dup), None)
for p in players_with_dup:
    if name_to_id_first[p.name] is None:
        name_to_id_first[p.name] = p.id

print(name_to_id_first)

输出:

{'Alice': 123, 'Bob': 456}

方式2:遍历时判断键是否已存在

这种写法更直观,适合需要自定义逻辑的场景:

name_to_id_first = {}
for p in players_with_dup:
    if p.name not in name_to_id_first:
        name_to_id_first[p.name] = p.id

两种方式都能保证只保留首次出现的键值对,后者代码更易懂,前者适合追求简洁的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:34:55