我正在尝试从csv文件创建一个字典。 csv文件的第一列包含唯一键,第二列包含值。 csv文件的每一行代表字典中唯一的键值对。我试图使用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文件创建一个字典?谢谢。
我相信你要找的语法如下:
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 pandas as pd
dict = {row[0] : row[1] for _, row in pd.read_csv("file.csv").iterrows()}
通过调用open然后csv.DictReader
打开文件。
input_file = csv.DictReader(open("coors.csv"))
您可以通过遍历input_file来迭代csv文件dict reader对象的行。
for row in input_file:
print row
或仅访问第一行
dictobj = csv.DictReader(open('coors.csv')).next()
import csv
reader = csv.reader(open('filename.csv', 'r'))
d = {}
for row in reader:
k, v = row
d[k] = v
你必须将csv.reader转换为dict:
~ >> 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'}
这不是优雅,而是使用熊猫的一线解决方案。
import pandas as pd
pd.read_csv('coors.csv', header=None, index_col=0, squeeze=True).to_dict()
如果要为索引指定dtype(如果因使用bug而使用index_col参数,则无法在read_csv中指定):
import pandas as pd
pd.read_csv('coors.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
你也可以使用numpy。
from numpy import loadtxt
key_value = loadtxt("filename.csv", delimiter=",")
mydict = { k:v for k,v in key_value }
我建议添加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