Skip to content
Advertisement

KeyError in the .append() function, when translating csv to json

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

Here is my code

JavaScript

Traceback:

JavaScript

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

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement