将csv文件转换为字典列表

时间:2014-02-05 08:34:56

标签: python list csv dictionary

我有一个csv文件

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

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

输出为:

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

我该怎么做?

7 个答案:

答案 0 :(得分:52)

使用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)]
...
>>> a
[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}]

答案 1 :(得分:5)

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

答案 2 :(得分:3)

另一个更简单的答案:

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

答案 3 :(得分:1)

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

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))})

答案 4 :(得分:1)

# 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]

答案 5 :(得分:0)

将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)

答案 6 :(得分:0)

要将CSV文件(两列,多行,无标题)转换为词典列表,我使用了csv module。我的csv文件如下所示:

c1,-------- 
c14,EAE23ED3 
c15,-------- 

我想创建一个字典列表,将csv文件的每一行都作为字典(键,值对)。我想要的输出是:

[
{
    "c1": "--------"
}, 
{
    "c14": "EAE23ED3"
}, 
{
    "c15": "--------"
}
]

为此,我使用了以下代码:

import csv

csv_path = '.../input_file.csv'

mylist = []
mydict = {}

# read the csv and write to a dictionary
with open(csv_path, 'rb') as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        mydict = {row[0]:row[1]}
        mylist.append(mydict)

print(mylist)

在我的情况下有效。为了解决我的问题,这些帖子很有帮助: