从csv文件创建字典? [英] Creating a dictionary from a csv file?
问题描述
我试图从csv文件创建一个字典。 csv文件的第一列包含唯一键,第二列包含值。 csv文件的每一行都表示字典中的唯一键,值对。我尝试使用 csv.DictReader
和 csv.DictWriter
classes,但我只能找出如何为每一行生成一个新的字典。我想要一个字典。这里是我想要使用的代码:
I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the csv.DictReader
and csv.DictWriter
classes, but I could only figure out how to generate a new dictionary for each row. I want one dictionary. Here is the code I am trying to use:
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)
当我运行上面的代码时, c $ c> ValueError:太多值要解压缩(预期2)。如何从csv文件创建一个字典?谢谢。
When I run the above code I get a ValueError: too many values to unpack (expected 2)
. How do I create one dictionary from a csv file? Thanks.
推荐答案
我相信您要查找的语法如下:
I believe the syntax you were looking for is as follows:
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,您需要:
Alternately, for python <= 2.7.1, you want:
mydict = dict((rows[0],rows[1]) for rows in reader)
这篇关于从csv文件创建字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!