我正在尝试读取包含许多列的CSV文件,并将数组转储到字典中。第一行是字典的键,其余行是列表(键的值)。我尝试了以下但我有很多列可能会有所不同。
reader = csv.reader(open('CSV/Logger_data.csv', 'r'))
d = {}
for key,value in reader:
d[key] = value
DictReader似乎有效,但是当我通过迭代打印但是如何将数据存储在字典reader
中。这是我到目前为止所尝试的:
with open ('CSV/Logger_data.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row["DateTime"], row["Column1"])
答案 0 :(得分:2)
import csv
from itertools import chain
def get_mulList(*args):
return map(list,zip(*args))
csv_data = open('logger_data.csv','r')
data = list(csv.reader(csv_data))
ind_dict = dict(zip(data[0],get_mulList(*data[1:])))
print ind_dict
如果您的CSV是这样的,
'DateTime' 'Column1'
1-2-2012 a
2-3-2013 b
3-4-2014 c
从上面的脚本中你会得到这样的输出,
{
'DateTime':['1-2-2012','2-3-2013','3-4-2014'],
'Column1':['a','b','c']
}
答案 1 :(得分:0)
以下是一个例子:
import csv
d={}
with open("logger_data.csv","r") as csvf:
content = csv.reader(csvf, delimiter=";")
for row in content:
if not row[0] in d:
d[row[0]]=[]
for value in row[1:]:
d[row[0]].append(value);
对于csv文件“logger_data.csv”,如下所示:
AB; 123; 234; 345
ce; 1; 2; 3; 4
11; 99; 12; 123; 4; 5
输出:
{'ab': ['123', '234', '345'],
'ce': ['1', '2', '3', '4'],
'll': ['99', '12', '123', '4', '5']}