Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

need help on csv based program

I have watched the video, did the program as below.

import csv

with open("Book1.csv", newline='') as csvfile: reader = csv.DictReader(csvfile,delimiter='|') rows = list(reader) for row in rows[1:]: print(row['id'])

Output:Traceback (most recent call last): File "C:\Users\Admin PC\Desktop\csv_sample.py", line 9, in <module> print(row['id']) KeyError: 'id'

so,then I have printed 'print(row)', it returns OrderedDict([('id,name,graduation,percentage,specialization', '122,chinni,m.tech,77,ece')]), Can anybody explain why dict doesn't returning individual tuples?

Hi Vinay,

Could you please reformat the code in your question using this guide to formatting? Also, what video did you watch?

1 Answer

Looking over the documentation, it looks like DictReader produces a dictionary with keys of column names. I believe the issue here is that you've then used the list() function on the dictionary; something like the following might be what you're looking for?

import csv
with csv.DictReader(open("Book1.csv")) as csvfile:
  for row in csvfile:
    print(row["id"])