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!
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
CSV reading in Python: Is it a dictionary or a list?
So, I'm watching Kenneth read a csv file 4:45min in using csv.DictReader. Then I got stuck here... 'How does this work?!' You index like a list with "rows[1:3]" but then index like a dictionary with "row['group1']". I FINALLY realized that this is what you do when you have a list comprised of dictionaries and want to access a value in one of the dictionaries. I guess that's what we have here. But it STILL doesn't make sense because we used the list() function.... so I would think that the variable "rows" would be a list of tuples at best... and you can't index with a key in tuples.... well, I can't seem to. Any explanations why the example below (which I've recreated) works?
import csv with open('museum.csv', newline='') as csvfile: artreader = csv.DictReader(csvfile, delimiter='|') rows = list(artreader) for row in rows[1:3]: print(row['group1'])
Chris FreemanTreehouse Moderator 68,404 Points
Let's dig into the object being created by cvs.DictReader. A
cvs.DictReader returns an iterator that produces each row as needed. To get all of the rows into a list, an iterator can be wrapped with
list() to creat a
list. In this case, all the data goes into the list
rows. When no
fieldnames argument is provided,
cvs.DictReader uses the data in first row (i.e., row) as the field names when creating the
OrderedDict objects. Returning rows as
OrderedDict objects is new in Python 3.6.
Hope this helps. Post back if you need more help. Good Luck!
Wow, great answer... thanks Chris! This link may be helpful too others like it was to me in explaining iterator vs interable: https://stackoverflow.com/questions/9884132/what-exactly-are-pythons-iterator-iterable-and-iteration-protocols