Welcome to the Treehouse Community
Looking to learn something new?
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 67,989 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