Kickstart 2020 with new opportunities! - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
7. Importing CSV contents using custom field names
Summary

Instruction

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:
line_count = 0
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.

Exercise

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']