dictreader读取csv转换为字典list的优雅方法
在处理CSV文件时,我们经常需要将数据转换为更易操作的字典列表格式。Python的csv.DictReader提供了一种非常优雅的方式来完成这个任务。
import csv
def csv_to_dict(file_path):
"""
将CSV文件读取为字典列表
Args:
file_path: CSV文件路径
Returns:
list: 包含字典的列表,每个字典代表一行数据
"""
with open(file_path, 'r', encoding='utf-8') as file:
reader = csv.DictReader(file)
data = [row for row in reader]
return data
假设有一个 users.csv 文件:
name,age,city
张三,25,北京
李四,30,上海
王五,28,广州
使用方法:
# 读取CSV文件
data = csv_to_dict('users.csv')
# 输出结果
print(data)
输出结果:
[
{'name': '张三', 'age': '25', 'city': '北京'},
{'name': '李四', 'age': '30', 'city': '上海'},
{'name': '王五', 'age': '28', 'city': '广州'}
]