Mapping CSV Rows to Dictionaries

30 minutes
  • 2 Learning Objectives

About this Hands-on Lab

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) in csv_dict_conversion.py. The filename will be provided in the main 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 function def 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.

Additional Resources

You work in the IT department of a school district. The district has switched to a new Learning Management System (LMS) to track grades. The new system only takes grade data in CSV format, and outputs information as CSV. Teachers have an app that can read a list of dictionaries and will aid them in entering the grades from the students.

Your job is to test that you can create a list of dictionaries out of the CSV file and then test that you can convert the dictionaries back into an updated CSV file.

To this end, you have created a test sample class and retrieved the CSV file for that class.

Logging In

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab overview page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in a web browser. If you'd like to go this route, then you will need to navigate to the public IP address of the workstation server (provided in the hands-on lab page) on port 8080 (example: http://PUBLIC_IP:8080). Your password will be the same password that you'd use to connect over SSH.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!

Get Started
Who’s going to be learning?