Thursday, August 9, 2012

Python's csv.DictReader returns...

I spent a few hours banging my head against what now seems like something that should have been pretty easy to figure out, except I haven't coded in 20 years so a lot of the time although I have a general idea what I'm doing, figuring out the specifics and finding and understanding the online help (of all sorts) is really difficult. When I learned to code, there was no online help.

csv.DictReader.... it doesn't return a Python dictionary object. (It returns a... list? of dictionaries...)

Seems like it would, given the name, but no. And that was so difficult to figure out (thus, have to make a blog post out of it).

The csv library is great for dealing with data (since it deals with csv files). And Python dictionaries are pretty cool. But the csv.DictReader object is not a dictionary object.

It's like, if you hand it 100 things, and expect one big dictionary with 100 entries, you don't get that. You get back 100 little dictionaries of one entry each.

I haven't yet used Python's dictionaries at all, but I think the benefit to the csv object is it iterates better. I assume there's some reason to do it that way, but if I understood that, I wouldn't have had any problems in the first place.

Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames.
"Into a dict....", so, a dictionary object, right? No.