Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Write Dictionaries as CSV Records (Solution)

00:00 Just like with the list of lists before, we can grab the list of dictionaries provided through the exercise instructions and paste it into our solution. At the top of the file, we’ll need to define the usual set of import statements for manipulating CSV files, and we’ll need to specify the path to that file, which is located in my home directory and is named favorite_colors.csv.

00:30 Next, we’re going to open that file for writing,

00:44 and here we’ll have to create the CSV writer object. However, since the rows are no longer represented by lists, we don’t necessarily want to use the regular writer object.

00:56 Instead, it’ll be convenient to create an instance of the more specialized DictWriter and wrap the file with it. Now, because the expected output must start with a headline, we can tell the writer object what the desired column names are by specifying the optional fieldnames parameter, which must be a sequence of strings. In this case, the first column is called name, and the second one is called favorite_color.

01:23 It’s important that the fieldnames that you specify here are exactly equal to the keys in your favorite_colors dictionary. Otherwise, you might get a ValueError later on.

01:34 The DictWriter object won’t save these field names automatically unless we call the .writeheader() method. So that’s what I’ll do now.

01:44 Finally, we can write the rows and pass the dictionary as an argument because that’s what the DictWriter expects.

01:56 All right, let’s save this file as exercise_02_03 and run the code.

02:06 No errors, which is a good sign. That means the CSV file with favorite colors was created successfully, so we can try and open it in IDLE to verify its content.

02:22 And it looks fine. The file begins with a headline and follows the correct CSV format, with each row representing someone’s name and their favorite color. Great. You can move on to the next exercise.

Become a Member to join the conversation.