Reputation: 1265
I am trying to read a CSV file which contains a number of columns and dump the array into a dictionary. First row would be a key of dictionary, and the rest of the rows are list (values of key). I tried the following but I have loads of columns which may vary.
reader = csv.reader(open('CSV/Logger_data.csv', 'r'))
d = {}
for key,value in reader:
d[key] = value
DictReader seems to work but when I print through iterating but how can I store the data in a dictionary reader
. This is what I tried so far:
with open ('CSV/Logger_data.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row["DateTime"], row["Column1"])
Upvotes: 2
Views: 3701
Reputation: 20147
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
if your CSV is like this,
'DateTime' 'Column1'
1-2-2012 a
2-3-2013 b
3-4-2014 c
from the above script you will get output like this,
{
'DateTime':['1-2-2012','2-3-2013','3-4-2014'],
'Column1':['a','b','c']
}
Upvotes: 2
Reputation: 573
Here is an example:
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);
For the csv file "logger_data.csv" looking like this:
ab;123;234;345
ce;1;2;3;4
ll;99;12;123;4;5
Output:
{'ab': ['123', '234', '345'],
'ce': ['1', '2', '3', '4'],
'll': ['99', '12', '123', '4', '5']}
Upvotes: 0