Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting KeyError when accessing third column of CSV using DictReader [duplicate]

Tags:

python

csv

I try to use Python to sort a csv file by date (newest entries first). The column of the csv file that contains dates is the third column of the csv file.

When I run the code below, I get the following error message:

KeyError: 2

Could you please provide me guidelines to correct my script below:

import csv
import os
from csv import writer
from datetime import datetime

with open("data.csv", newline="") as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=",")
sortedlist = sorted(spamreader, key=lambda row: datetime.strptime(row[2]), reverse=False)

with open("sortdata.csv", "w") as f:
    fieldnames = ["detection_date"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for row in sortedlist:
        writer.writerow(row)
like image 890
mollieda Avatar asked May 04 '26 19:05

mollieda


1 Answers

Just reading the error, keyerror: 2, my eye goes to , datetime.strptime(row[2]).

You're trying to use a 0-based column index number for a DictReader, which expects a column name (which is derived from the first line (row) of data in your file, which it expects to be a "header").

So, swap row[2] out for row['third_column_name'] and you should be good.

If you don't have a header, use csv.reader().

like image 94
Zach Young Avatar answered May 06 '26 08:05

Zach Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!