Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Reading CSV files
7. Importing CSV contents using custom field names


Good job! If for some reason you don't like the field names that csv.DictReader() acquired from the header row, you can instead specify your own field names:

import csv
with open('departments.csv') as csv_file:
  csv_reader = csv.DictReader(csv_file, fieldnames=['Department Name', 'Number of Employees', 'Department Budget'])
  line_count = 0
  for row in csv_reader:
    if line_count > 0 and float(row['Department Budget']) > 350000.0:
      print('The', row['Department Name'], 'department has a budget of', row['Department Budget'], 'USD.')
    line_count += 1

csv.DictReader() has an optional parameter named fieldnames. By default, when you don't specify this argument, csv.DictReader() simply interprets the first row of the CSV as the header. The optional parameter accepts a list of string values that will be used as field names in the dictionary. Note that the number of field names you provide must match the number of fields in the CSV.

Now, we use row['Department Name'] instead of row['department'] to access the same information as before.


Modify the template code so it uses the following field names: 'FirstName', 'Sex', 'Country', 'Age', 'Weight'.

Stuck? Here's a hint!

Add the following optional parameter to the DictReader:

fieldnames=['FirstName', 'Sex', 'Country', 'Age', 'Weight']