KeyError in CSV Parsing Code

KeyError in CSV Parsing Code
KE
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 2
0

Hello,

I am facing an issue with my Python code and need any assistance.
I am trying to parse a CSV file and store the data in a dictionary. I am getting a KeyError.

import csv

data = {}
with open('file.csv', mode='r') as file:
reader = csv.DictReader(file)
for row in reader:
key = row['id']
data[key] = row['value']

The exact error message I receive is below-

KeyError: 'id'

I have checked that the 'file.csv' file exists and verified that it has the correct headers. The issue persists despite these checks.
I expected to get a dictionary where IDs are keys and their corresponding values are stored. Instead, I get a KeyError indicating that the 'id' key is missing.

I’m using Python 3.9.7.

The code is running on Windows 10 and uses the csv module.

Thank you in advance for any help you can provide!

Thank you
kevinsfmc

Spine
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 6964
2

CSV: Comma Separated Values.
You could check COMMA (SEPARATOR) in your CSV file.
See documentation: https://docs.python.org/3/library/csv.html

In the example reader is created with custom delimiter. It's space instead of comma or semicolon:

Kopiuj
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')

CSV files are so simple you could make your own parser. No need to use CSV module.
Read all lines of the text file and separate them with split method.

lion137
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 5023

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.