CSV files are an efficient and very common way to move data around. The can be imported into Excel very easily for review and editing, and then exported to CSV for other operations. They can also easily be imported into pandas dataframes for work.
So in this lab we will use Python’s `csv` module to read CSV into dictionaries, allow the intended user to make necessary operations on the data in the dictionaries, and then return them to CSV for further operations.
You will need to know basic Python programming and have knowledge of Python’s `csv` module:
– [Certified Associate in Python Programming Certification](https://linuxacademy.com/cp/modules/view/id/470)
Learning Objectives
Successfully complete this lab by achieving the following learning objectives:
- Convert a CSV File to a List of Dictionaries
The LMS provides a CSV file for the test class named
student_data.csv
. You have a skeleton app that will let you write code to test the ability to make the CSV data into a dictionary.Before writing code, please run the file to see what is failing:
python csv_dict_conversion.py
You will get a message that "the returned data does not match the expected dict." So please complete the function
def csv2dict(filename)
incsv_dict_conversion.py
. The filename will be provided in themain
function of the file.def csv2dict(filename): # open file and create DictReader object # use the DictReader to get data and # add data to a variable named data_list with open(filename, newline='') as infile: reader = csv.DictReader(infile) data = [] for row in reader: data.append(row) return data
Run
python csv_dict_conversion.py
.Congratulations! The data is in a format the teacher’s app can use.
- Convert a List of Dictionaries to CSV
The main function simulates that the teacher has added the grades.
Please run
python csv_dict_conversion.py
. You should see an error that "the written data does not match the expected data." Please complete the functiondef dict2csv(filename, fieldnames, data)
. The filename and fieldnames are provided for you. The data is the dictionary data created in the last objective with the grades added. This is also provided for you.def dict2csv(filename, fieldnames, data): # open file and create DictWriter object # use the DictWriter to write csv data # to file with open(filename, 'w', newline='') as outfile: writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(data) Run `python csv_dict_conversion.py`. **Awesome!** You have mastered moving data from CSV to dictionaries and dictionaries to CSV.