python – Creating a dictionary from a csv file?
python – Creating a dictionary from a csv file?
I believe the syntax you were looking for is as follows:
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 = {rows[0]:rows[1] for rows in reader}
Alternately, for python <= 2.7.1, you want:
mydict = dict((rows[0],rows[1]) for rows in reader)
Open the file by calling open and then using csv.DictReader.
input_file = csv.DictReader(open(coors.csv))
You may iterate over the rows of the csv file dict reader object by iterating over input_file.
for row in input_file:
print(row)
OR
To access first line only
dictobj = csv.DictReader(open(coors.csv)).next()
UPDATE
In python 3+ versions, this code would change a little:
reader = csv.DictReader(open(coors.csv))
dictobj = next(reader)
python – Creating a dictionary from a csv file?
import csv
reader = csv.reader(open(filename.csv, r))
d = {}
for row in reader:
k, v = row
d[k] = v