DictReader and DictWriter Objects

The csv module provides us with additional useful objects: the DictReader and DictWriter objects, which are similar to the csv.reader and csv.writer objects.

If you follow the convention that places a header at the beginning of a CSV file, that is, that each column in the CSV file starts with a field name (see Chapter 4 for a discussion of this), accessing values can be done by accessing the dictionary with the field name as key.

Let's turn to an example. To follow along, create the file ../data/tobuy.csv with the following content:

Item,Count Milk,2 Eggs,12 Tomatoes,5

Now let's create a DictReader object: >>> import csv

>>> fcsv = open('../data/tobuy.csv') >>> for row in csv.DictReader(fcsv): ... print "Please buy ", row['Count'], row['Item']

Please buy 2 Milk Please buy 12 Eggs Please buy 5 Tomatoes

I've accessed the values in the CSV file using 'Count' and 'Item' as keys to the dictionary object, row: row['Count'] and row['Item']. If columns were switched, the code would still work as expected.

Similarly, you can create a DictWriter object as follows:

>>> rows = [['Organic Eggs', 5], ['Cucumbers', 12]] >>> fcsv = open('../data/tobuy_more.csv', 'wb') >>> dict_wr = csv.DictWriter(fcsv, header)

>>> dict_wr.writerow(dict(zip(header, header))) >>> for row in rows:

... dict_wr.writerow(dict(zip(header, row))) >>> fcsv.close()

I first created the header, a list of strings, and the data, a list of rows. I then opened a file named ../data/tobuy more.csv for writing and attached it to a csv.DictWriter object named dict wr. As you can see, csv.DictWriter requires the header information as well.

Now this is where it gets a little tricky. First, I'd like to write the header information to the CSV file. To do so, I create the following dictionary:

>>> dict(zip(header, header)) {'Count': 'Count', 'Item': 'Item'}

I then pass this dictionary as a parameter to the function writerrow(), a method of DictWriter, in essence creating the header field.

Now, all that's required is to do the same for the data, that is:

... dict_wr.writerow(dict(zip(header, row))) And here are the results:

Item,Count Organic Eggs,5 Cucumbers,12

As you can see, the DictWriter object is not as simple to work with. That's why I rarely use it, although I use DictReader quite a bit. For a full account of DictReader and DictWriter, please consult with the Python Library Reference.

+2 0

Average user rating: 5 stars out of 2 votes

Post a comment

  • Receive news updates via email from this site