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:

KeyError: 0

Here is my code

#Open file 
Open file
with open(filename, "r") as f:
        sampleReader = csv.DictReader(f)
        next(sampleReader)
        data = {"test":[]}
        for row in sampleReader:
            data["test"].append({"ACTIVITY DATE": row[0]})
        print(data)

Traceback:

KeyError                                  Traceback (most recent call last)
<ipython-input-4-582fa1fa84a1> in <module>
      5         data = {"test":[]}
      6         for row in sampleReader:
----> 7             data["test"].append({"ACTIVITY DATE": row[0]})
      8         print(data)
      9 

KeyError: 0

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:

sampleReader = csv.reader(f)

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:

with open(filename, "r") as f:
        sampleReader = csv.DictReader(f)
        data = {"test":[]}
        for row in sampleReader:
            data["test"].append({"ACTIVITY DATE": row['activity date']})
        print(data)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement