Read CSV Records as Dictionaries (Solution)
Reading a CSV file containing a headline into a list of dictionaries requires creating a
DictReader object. But first, we need to include the usual bit of boilerplate code that we’ve been typing over and over again.
Now we can define a
Path instance pointing to the
favorite_colors.csv file in the home directory. If you haven’t completed the previous exercise, then you can find the required CSV file in the supporting materials available for download.
Alternatively, you can create the file manually and copy its content from the slides. We can now open the file for reading using the
with statement, remembering to set the character encoding and disable the universal newline.
01:27 When it does, the reader object can infer the corresponding column names from the first row, assuming it’s the header line. Otherwise, you must specify the field names explicitly when creating the reader object.
When you do, the
fieldnames parameter takes precedence and the headline present in the file will be treated as regular data. So you should generally know if your CSV file includes a headline or not before proceeding to avoid any confusion or problems in your data processing.
In this case, I’ll let the reader perform the inference by not specifying the column names myself because I know that our file comes with a headline. Now, the
DictReader happens to be an adapter for the standard CSV reader providing the conversion between the rows and Python dictionaries.
Become a Member to join the conversation.