[Csv] Re: dict argument to writer.writerow

Skip Montanaro skip at pobox.com
Thu Feb 6 06:59:02 CET 2003


    Andrew> I don't think this belongs in writer.writerow - I'd suggest it
    Andrew> belongs in the as yet unwritten csv.util module. The problem is
    Andrew> that it's going to have an appreciable impact on the normal case
    Andrew> of writing a tuple.

Hmmm...  I think of reading/writing dicts as more integration with the DB
API.  I rarely use plain fetchall() when getting rows from a table.
Dictionaries are much saner objects.  Accordingly, I'd like it to be as
painless as possible for people to write them out to CSV files.

Also, one can frequently think of CSV files as a file of dicts with the
simple optimization that the dictionary keys are only written once, in the
first row.

That's not to say my code couldn't have been done differently.  I was trying
hard to avoid testing the type of the object being written.  In retrospect
the code I have will cause an exception to be raised and caught most of the
time.  Perhaps it would be better as:

    if hasattr(fields, "has_key"):
        # if fields is a dict, we need a valid fieldnames list
        # if self.fieldnames is None we'll get a TypeError in the for stmt
        # if fields is not a dict we'll get an AttributeError on .get()
        try:
            flist = []
            for k in self.fieldnames:
                flist.append(fields.get(k, ""))
            fields = flist
        except (TypeError, AttributeError):
            pass

That should lessen the load in the common case (call to hasattr() vs raised
and caught exception).  Alternatively, perhaps a writedict() method makes
sense.  It would be extremely rare (and nearly insane) for a user to write a
mixture of lists and dicts.  The user could either know what type of row to
write and call the proper method or test the type of the first row outside
the loop and assign a variable to the appropriate method.

In any case, I'd like it to be as easy as possible for people to write dicts
to CSV files and read rows into dicts as possible.

Skip


More information about the Csv mailing list