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

如何将指定CSV数据转换为剔除冗余字段的目标Python字典?

解决方案

修改后的完整可运行代码如下:

import csv

csvfile = "你的CSV文件路径.csv" # 替换为你实际的CSV文件存储路径
Columns = "Column1","Column2","Column3","Column4","Column5"
cols = col1,col2,col3,col4,col5 = [],[],[],[],[]
refs = [] # 新增存储ref取值的列表

with open(csvfile,'r',encoding="utf8") as f:
    reader = list(csv.reader(f))
    # 从第二行开始遍历,跳过CSV表头行
    for line in reader[1:]:
        # 仅遇到Column1行时记录ref,避免同一个ref重复添加
        if line[1] == "Column1":
            refs.append(int(line[0]))
        for i,col in enumerate(Columns):
            if col == line[1]:
                cols[i].append(line[4])

# 组装为目标字典
thisdict = {"ref": refs}
for col_name, col_list in zip(Columns, cols):
    thisdict[col_name] = col_list

print(thisdict)

运行后输出结果和要求的目标结构完全匹配:

{'ref': [1, 2, 3], 'Column1': ['text11', 'text21', 'text31'], 'Column2': ['text12', 'text22', 'text32'], 'Column3': ['text13', 'text23', 'text33'], 'Column4': ['text14', 'text24', 'text34'], 'Column5': ['text15', 'text25', 'text35']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:39:01