2014-02-05 135 views
18

的名單我有一個CSV文件轉換CSV文件到字典

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

我想從這個CSV創建字典的列表。

輸出:

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

我怎樣才能做到這一點?

回答

35

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

專爲懶人設計的列表,從鏈接頁面 - 'skipinitialspace':當TRUE;,緊接分隔符後面的空白將被忽略。 – Flash

+0

@falsetru,這裏爲什麼輸出不是按這個順序來的? [{'col1':1,'col2':2,'col3':3},{'col1':4,'col2':5,'col3':6}] –

+0

@VT,Dictionary in python 3.6 - 不是有序的集合。 – falsetru

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}] 
1

好,而其他人出來做這件事聰明的方式,我實現了它vely。我想我的方法具有不需要任何外部模塊的好處,但它可能會失敗,並出現奇怪的值配置。這只是供參考:

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))}) 
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] 
+0

只能得到相同順序的CSV –

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)