I am attempting to fill a default dictionary with csv data, and I am getting a key error
for i in range(0,1):
#https://docs.python.org/2/library/collections.html#collections.defaultdict
result = co.defaultdict(list)
with open(os.path.join(inputdir,tablelist[i])) as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
read = csv.DictReader(f)
for line in read:
for j in range(1,len(csv_headings)):
error here--->result[line[csv_headings[0]]].append(line[csv_headings[j]])
for csv data
API,CNTYNM,PRMT,
4700100002,Barbour,2,
4700100003,Barbour,3,
4700100004,Barbour,4,
the key error is for API which means to me that something with dictreader is not working as expected can anyone give some advice?
You are missing fieldnames
argument to DictReader
. If you modify your code to pass csv_haedings
to DictReader
it will work (hopefully as expected):
for i in range(0,1):
#https://docs.python.org/2/library/collections.html#collections.defaultdict
result = co.defaultdict(list)
with open(os.path.join(inputdir,tablelist[i])) as f:
csv_reader = csv.reader(f)
csv_headings = next(csv_reader)
read = csv.DictReader(f, fieldnames=csv_headings)
for line in read:
for j in range(1,len(csv_headings)):
result[line[csv_headings[0]]].append(line[csv_headings[j]])