如何在Python中读取CSV并转为以表头为键的字典(不使用Pandas)
解决方案:用csv模块将CSV数据转为表头键名的字典
原代码直接跳过了表头,且文件操作逻辑放在类的顶层代码块(会在类加载时就执行),我们可以调整结构,保留表头并生成符合需求的字典结构,无需依赖Pandas:
完整实现代码
import csv class CsvReader: @classmethod def read_as_dicts(cls, file_path="Items.csv"): with open(file_path, mode='r', newline='', encoding='utf-8') as fp: reader = csv.reader(fp, delimiter=",", quotechar='"') # 读取表头行,而非直接跳过 headers = next(reader) data_dicts = [] for row in reader: # 将表头与行数据配对成字典 item_dict = dict(zip(headers, row)) # 数据清洗与类型转换,匹配期望输出格式 item_dict['Item #'] = int(item_dict['Item #']) item_dict['Price'] = float(item_dict['Price'].replace('$', '')) item_dict['Quantity'] = int(item_dict['Quantity']) data_dicts.append(item_dict) return data_dicts # 使用示例 if __name__ == "__main__": items = CsvReader.read_as_dicts() print(items[0])
代码说明
- 将读取逻辑封装为类方法
read_as_dicts,既符合面向对象规范,也支持灵活指定文件路径 - 用
next(reader)获取表头行,后续通过dict(zip(headers, row))快速生成键值对字典 - 针对示例数据做了类型转换:编号、Quantity转为整数,Price去掉
$符号后转为浮点数,与你期望的输出格式完全匹配 - 添加
newline=''和编码指定,避免跨平台换行符问题与编码错误
输出结果
{'Item #': 1, 'Price': 5.99, 'Quantity': 1, 'Name': 'Blueberry Muffin'}
如果你的CSV表头或数据格式有变动,只需调整类型转换部分的逻辑即可适配。
内容的提问来源于stack exchange,提问作者Fear_Schwier
相关产品推荐
相关产品推荐

