将 csv 文件转换为字典列表

Posted

技术标签:

【中文标题】将 csv 文件转换为字典列表【英文标题】:convert csv file to list of dictionaries 【发布时间】:2014-03-01 14:01:40 【问题描述】:

我有一个 csv 文件

col1, col2, col3
1, 2, 3
4, 5, 6

我想从这个 csv 创建一个字典列表。

输出为:

a= ['col1':1, 'col2':2, 'col3':3, 'col1':4, 'col2':5, 'col3':6]

我该怎么做?

【问题讨论】:

【参考方案1】:

使用csv.DictReader:

import csv

with open('test.csv') as f:
    a = [k: int(v) for k, v in row.items()
        for row in csv.DictReader(f, skipinitialspace=True)]

将导致:

['col2': 2, 'col3': 3, 'col1': 1, 'col2': 5, 'col3': 6, 'col1': 4]

【讨论】:

对于懒人,来自链接页面 - skipinitialspace:当True 时,紧跟在分隔符后面的空格将被忽略。 @falsetru,为什么输出没有按这个顺序出现? ['col1':1, 'col2':2, 'col3':3, 'col1':4, 'col2':5, 'col3':6] @V-T,如果你使用 Python 3.6+,OrderedDict 保证顺序:docs.python.org/3/library/csv.html#csv.DictReader @hpy,从 Python 3.7+ 开始,保证 dict 的插入顺序。 mail.python.org/pipermail/python-dev/2017-December/151283.html => 不用担心,使用 DictReader :) @hpy,在"What's New In Python 3.7 - Summary - Release Hightlights" 中提到> Python 数据模型改进:> dict 对象的插入顺序保存性质已被声明为 Python 语言规范的官方部分。【参考方案2】:

将 CSV 解析为字典列表的简单方法

with open('/home/mitul/Desktop/OPENEBS/test.csv', 'rb') as infile:
  header = infile.readline().split(",")
  for line in infile:
    fields = line.split(",")
    entry = 
    for i,value in enumerate(fields):
      entry[header[i].strip()] = value.strip()
      data.append(entry)

【讨论】:

【参考方案3】:

另一个更简单的答案:

    import csv
    with open("configure_column_mapping_logic.csv", "r") as f:
        reader = csv.DictReader(f)
        a = list(reader)
        print a

【讨论】:

这会将它变成一个元组列表,而不是字典? print(a) 应该在 with 块之外,因为那时不再需要该文件。另外:为什么不a = list(csv.DictReader(f))【参考方案4】:
# similar solution via namedtuple:    

import csv
from collections import namedtuple

with open('foo.csv') as f:
  fh = csv.reader(open(f, "rU"), delimiter=',', dialect=csv.excel_tab)
  headers = fh.next()
  Row = namedtuple('Row', headers)
  list_of_dicts = [Row._make(i)._asdict() for i in fh]

【讨论】:

只回答得到相同顺序的 CSV【参考方案5】:

好吧,虽然其他人都在以聪明的方式做这件事,但我却天真地实现了它。我想我的方法的好处是不需要任何外部模块,尽管它可能会因值的奇怪配置而失败。这里仅供参考:

a = []
with open("csv.txt") as myfile:
    firstline = True
    for line in myfile:
        if firstline:
            mykeys = "".join(line.split()).split(',')
            firstline = False
        else:
            values = "".join(line.split()).split(',')
            a.append(mykeys[n]:values[n] for n in range(0,len(mykeys)))

【讨论】:

【参考方案6】:

使用csv 模块和列表推导:

import csv
with open('foo.csv') as f:
    reader = csv.reader(f, skipinitialspace=True)
    header = next(reader)
    a = [dict(zip(header, map(int, row))) for row in reader]
print a    

输出:

['col3': 3, 'col2': 2, 'col1': 1, 'col3': 6, 'col2': 5, 'col1': 4]

【讨论】:

以上是关于将 csv 文件转换为字典列表的主要内容,如果未能解决你的问题,请参考以下文章

将 csv.DictReader 对象转换为字典列表?

将带有字典列表的 defaultdict(list) 字典转换为 csv 的最佳方法

将字典转换为 CSV 文件 [重复]

如何将CSV文件转换为python字典

将 CSV 文件的内容转换为字典

将CSV文件转换为Python字典,数组和二进制文件