python - 将csv转换为python中的字典列表
问题描述
我有一个 CSV 文件,其中第一行是标题,然后其他行是列中的数据。
我正在使用 python 将这些数据解析到字典列表中
通常我会使用这个代码:
def csv_to_list_of_dictionaries(file):
with open(file) as f:
a = []
for row in csv.DictReader(f, skipinitialspace=True):
a.append({k: v for k, v in row.items()})
return a
但是因为一列中的数据存储在字典中,所以这段代码不起作用(它分隔了这个字典中的键:值对
所以我的 csv 文件中的数据如下所示:
col1,col2,col3,col4
1,{'a':'b', 'c':'d'},'bla',sometimestamp
从此字典创建如下:{col1:1, col2:{'a':'b', col3: 'c':'d'}, col4: 'bla'}
我希望得到的结果是:{col1:1, col2:{'a':'b', 'c':'d'}, col3: 'bla', col4: sometimestamp}
解决方案
不要使用 csv 模块使用正则表达式从每一行中提取字段。然后从提取的行中制作字典。
示例文件:
col1,col2,col3,col4
1,{'a':'b', 'c':'d'},'bla',sometimestamp
2,{'a':'b', 'c':'d'},'bla',sometimestamp
3,{'a':'b', 'c':'d'},'bla',sometimestamp
4,{'a':'b', 'c':'d'},'bla',sometimestamp
5,{'a':'b', 'c':'d'},'bla',sometimestamp
6,{'a':'b', 'c':'d'},'bla',sometimestamp
.
import re
pattern = r'^([^,]*),({.*}),([^,]*),([^,]*)$'
regex = re.compile(pattern,flags=re.M)
def csv_to_list_of_dictionaries(file):
with open(file) as f:
columns = next(f).strip().split(',')
stuff = regex.findall(f.read())
a = [dict(zip(columns,values)) for values in stuff]
return a
stuff = csv_to_list_of_dictionaries(f)
In [20]: stuff
Out[20]:
[{'col1': '1',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'},
{'col1': '2',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'},
{'col1': '3',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'},
{'col1': '4',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'},
{'col1': '5',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'},
{'col1': '6',
'col2': "{'a':'b', 'c':'d'}",
'col3': "'bla'",
'col4': 'sometimestamp'}]
推荐阅读
- python - 在 Huggingface BERT 模型之上添加密集层
- json - 从框架的 JSON-LD 中删除额外的参数
- scala - 从Scala中的YYYYMM日期减去月份
- c# - C#。如何将高斯钟形曲线应用于我的峰值?
- wordpress - WordPress Gutenberg 查看编辑器的帖子
- amazon-web-services - 在 Docker 容器中运行时出现 Boto3 ConnectionClosedError - 错误:在我们收到来自端点 URL 的有效响应之前,连接已关闭
- python - Discord 机器人无法正常工作
- c# - 使用内联映射的 Automapper 自定义解析器导致测试失败
- google-cloud-platform - 将 Cloud SQL 连接到 BigQuery(错误:找不到方法)
- react-proptypes - 在自定义验证器中使用常规 PropTypes 检查