首页 > 解决方案 > 将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}

标签: pythonlistcsvdictionary

解决方案


不要使用 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'}]


推荐阅读