如何在Python中将列长度不一的.csv文件读取为字典
读取列长度不一致的CSV并转换为指定格式字典
针对你已实现的CSV写入逻辑,以下是对应的读取代码,能将列长度不一致的CSV还原为以列名为键、列值列表为值的字典:
import csv import itertools path = 'C:/Users/.../test.csv' out_dict = { 'Class1': ['A', 'B'], 'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'], 'Class3': ['J', 'K', 'L', 'M', 'N'] } # 写入字典到CSV with open(path, 'wt', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerow(out_dict.keys()) writer.writerows(itertools.zip_longest(*out_dict.values())) # 读取CSV为字典 with open(path, 'rt') as csv_file: reader = csv.reader(csv_file) # 获取表头作为字典的键 headers = next(reader) # 初始化空字典,每个键对应一个空列表 in_dict = {header: [] for header in headers} # 遍历每一行数据,将列值对应添加到列表,过滤空占位符 for row in reader: for header, value in zip(headers, row): if value: in_dict[header].append(value) print(in_dict)
关键说明:
- 读取时先用
next(reader)获取CSV第一行的表头,作为字典的键 - 初始化字典时为每个键创建空列表,用于收集对应列的所有值
- 遍历每行数据时,将每个列的非空值添加到对应列表,自动过滤掉写入时
zip_longest填充的空占位内容(对应原短列表的补位)
运行后输出将与你期望的结果完全一致:
{'Class1': ['A', 'B'], 'Class2': ['C', 'D', 'E', 'F', 'G', 'H', 'I'], 'Class3': ['J', 'K', 'L', 'M', 'N']}
内容的提问来源于stack exchange,提问作者rasputin
相关产品推荐
相关产品推荐

