CSV List Reader

Learn how to implement the CSV list reader in Python.

We'll cover the following

Overview

The non-dictionary CSV reader produces a list of strings from each row. This is not what our TrainingData collection’s load() method expects, however. We have two choices to meet the interface requirement for the load() method:

  1. Convert the list of column values to a dictionary.

  2. Change load() to use a list of values in a fixed order. This would have the unfortunate consequence of forcing the load() method of the TrainingData class to match a specific file layout. Alternatively, we’d have to re-order input values to match the requirements of load(); doing this is about as complex as building a dictionary.

Building a dictionary seems relatively easy; this allows the load() method to work with data where the column layout varies from our initial expectation.

Example

Here’s a CSVIrisReader_2 class that uses csv.reader() to read a file, and builds dictionaries based on the attribute information published in the iris.names file.

Get hands-on with 1200+ tech skills courses.