我正在尝试从 csv 文件创建字典。csv 文件的第一列包含唯一键,第二列包含值。csv 文件的每一行代表字典中唯一的键值对。我尝试使用csv.DictReaderandcsv.DictWriter类,但我只能弄清楚如何为每一行生成一个新字典。我想要一本字典。这是我尝试使用的代码:
csv.DictReader
csv.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 文件创建一个字典?谢谢。
ValueError: too many values to unpack (expected 2)
我相信您正在寻找的语法如下:
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 = {rows[0]:rows[1] for rows in reader}
或者,对于 python <= 2.7.1,您需要:
mydict = dict((rows[0],rows[1]) for rows in reader)