小编典典

Python-从CSV文件创建字典?

python

我正在尝试从csv文件创建字典。csv文件的第一列包含唯一键,第二列包含值。csv文件的每一行代表字典中的唯一键,值对。我尝试使用csv.DictReaderand 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文件创建一个字典?


阅读 1451

收藏
2020-02-18

共1个答案

小编典典

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

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)
2020-02-18