- [Instructor] So now that we've seen
how to write a CSV file as arrays, in this example,
we're going to see how to write a CSV file
using dictionaries for the data source instead of arrays.
So in this example code, let's open up write_csv_dict.py.
And I've already got a list of dictionary objects
that represent a subset of the data
in the inventory file that we've been using.
So you can see that this is a little bit
of a different format than we had in the previous example.
The first thing I need to do is define the column names
that will be the header row for the output CSV file.
This is required by the DictWriter object we're going
to be using in the CSV module, so it knows how
to map each dictionary key to a particular column.
So you can see in the sample data
that the items in each row consists of a key and a value.
The fieldnames parameter will be used to match
each of the keys to one of the output columns.
And this is required by the DictWriter.
This is not optional like it was in the reading example.
So what I'm going to do is create a fieldnames variable.
And that's going to be a list of the keys in my data.
So I'm going to have Item Name, Category, Quantity.
And then we'll have the Wholesale Price
and the Consumer Price.
And these need to match each of the keys
that you have in your dictionary.
So make sure that they're spelled correctly,
otherwise it's going to cause a problem.
All right, so now let's build our function
to write the CSV file.
So I'm going to call that write_dict_to_csv.
And once again, that will take the data and the filename.
So similar to the previous example,
we will open our file for writing.
So we'll open the filename in write mode with line endings.
Oops.
And we'll open that as CSV file.
Only this time, we're going to use a DictWriter
to write the data.
And this is where we supply the field names
that we've created.
So I'm going to create a writer variable
and that's going to be an instance of the DictWriter class.
And I'm going to pass in the CSV file that we created,
and I'm going to specify that fieldnames is equal
to the fieldnames variable that we've created.
And then we'll just write the data as usual.
So we'll call writer,
and I'm going to call writeheader first.
That will output all the field names as the header row.
And then I'll call writer.writerows,
and we'll pass in the array of dictionaries.
And once again, I just need to call the function
for all this to work.
So let's go ahead and call our function
and we'll pass in the data.
And once again we'll call it output.csv.
All right, so let's save, that should about do it.
Let's run our code.
So we'll run this in the terminal,
and when I run it, we can see output.csv was created
and everything looks good.
Take a look at that.
Sure enough, CSV data looks right.
We've got our header row, Item Name, Category, Quantity,
Wholesale, Consumer Price, along with all of the values
that we wrote out in our dictionaries.