Okay, so here is what Im trying to do. I am trying to take a csv file and translate this into a Json so i can compare data sets.
However, for some reason I am unable to find, when i try and append the headings there is an error:
JavaScript
x
2
1
KeyError: 0
2
Here is my code
JavaScript
1
10
10
1
#Open file
2
Open file
3
with open(filename, "r") as f:
4
sampleReader = csv.DictReader(f)
5
next(sampleReader)
6
data = {"test":[]}
7
for row in sampleReader:
8
data["test"].append({"ACTIVITY DATE": row[0]})
9
print(data)
10
Traceback:
JavaScript
1
10
10
1
KeyError Traceback (most recent call last)
2
<ipython-input-4-582fa1fa84a1> in <module>
3
5 data = {"test":[]}
4
6 for row in sampleReader:
5
----> 7 data["test"].append({"ACTIVITY DATE": row[0]})
6
8 print(data)
7
9
8
9
KeyError: 0
10
Advertisement
Answer
If you are to specify a field by its column number (as you do with row[0]
) rather than its column name, you should use csv.reader
instead of csv.DictReader
:
JavaScript
1
2
1
sampleReader = csv.reader(f)
2
If you would like to specify a field by its column name, you should not skip a row with next(sampleReader)
since csv.DictReader
already consumes the header row, and you should also use the desired column name as a key to retrieve the value of the field:
JavaScript
1
7
1
with open(filename, "r") as f:
2
sampleReader = csv.DictReader(f)
3
data = {"test":[]}
4
for row in sampleReader:
5
data["test"].append({"ACTIVITY DATE": row['activity date']})
6
print(data)
7