Refactoring a .csv DictReader as a dataclass reader
When we read data from a CSV format file, the csv
module offers two general choices for the kind of reader to create:
- When we use
csv.reader()
, each row becomes a list of column values. - When we use
csv.DictReader
, each row becomes a dictionary. By default, the contents of the first row become the keys for the row dictionary. An alternative is to provide a list of values that will be used as the keys.
In both cases, referring to data within the row is awkward because it involves rather complex-looking syntax. When we use the csv.reader()
function, we must use syntax like row[2]
to refer to a cell; the semantics of index 2 are completely obscure.
When we use csv.DictReader
, we can use row['date']
, which is less obscure, but this is still a lot of extra syntax. While this has a number of advantages, it requires a CSV with a single-row header of unique column names, which is something...