从csv文件创build一个字典?

我正在尝试从csv文件创build一个字典。 csv文件的第一列包含唯一键,第二列包含值。 csv文件的每一行表示字典中唯一的键值对。 我试图使用csv.DictReadercsv.DictWriter类,但我只能弄清楚如何为每一行生成一个新的字典。 我想要一本字典。 这是我想要使用的代码:

 import csv with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) for rows in reader: k = rows[0] v = rows[1] mydict = {k:v for k, v in rows} print(mydict) 

当我运行上面的代码,我得到一个ValueError: too many values to unpack (expected 2) 。 如何从csv文件创build一个字典? 谢谢。

我相信你正在寻找的语法如下:

 with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) mydict = {rows[0]:rows[1] for rows in reader} 

或者,对于python <= 2.7.1,您需要:

 mydict = dict((rows[0],rows[1]) for rows in reader) 
 import csv reader = csv.reader(open('filename.csv', 'r')) d = {} for row in reader: k, v = row d[k] = v 

通过调用open然后csv.DictReader打开文件。

 input_file = csv.DictReader(open("coors.csv")) 

您可以迭代csv文件dict阅读器对象的行遍历input_file。

 for row in input_file: print row 

或仅访问第一行

 dictobj = csv.DictReader(open('coors.csv')).next() 

你也可以用这个numpy。

 from numpy import loadtxt key_value = loadtxt("filename.csv", delimiter=",") mydict = { k:v for k,v in key_value } 

你必须把csv.reader转换成字典:

 ~ >> cat > 1.csv key1, value1 key2, value2 key2, value22 key3, value3 ~ >> cat > d.py import csv with open('1.csv') as f: d = dict(filter(None, csv.reader(f))) print(d) ~ >> python d.py {'key3': ' value3', 'key2': ' value22', 'key1': ' value1'} 

我会build议添加if rows ,以防在文件末尾有空行

 import csv with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) mydict = dict(row[:2] for row in reader if row) 

如果你可以使用numpy包,那么你可以做如下的事情:

 import numpy as np lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None) my_dict = dict() for i in range(len(lines)): my_dict[lines[i][0]] = lines[i][1] 

你可以使用这个,这很酷:

 import dataconverters.commas as commas filename = 'test.csv' with open(filename) as f: records, metadata = commas.parse(f) for row in records: print 'this is row in dictionary:'+rowenter code here