Sitemap
David W. Agler

David W. Agler

Assistant Teaching Professor - Philosophy. I make logic and philosophy videos at https://www.youtube.com/@LogicPhilosophy

Using Python CSV #4 — DictWriter

5 min readDec 23, 2022

--

Press enter or click to view image in full size

Basic Usage of DictWriter

In previous articles (#1 , #2 , and #3), I looked at three functions of thecsv module: csv.reader , csv.writer, and csv.DictReader. In this article, we’ll look at csv.DictWriter.

What does csv.DictWriter do?

In essence, csv.DictWriter creates a spreadsheet and maps lists of dictionaries to rows of a spreadsheet. Let’s start with a simple example. First, let’s say we have a list of dictionaries. In our first example, we will use a list that only contains one dictionary:

test_dict = [{'a':1, 'b':2, 'c': 3}]

Notice that our dictionary has three keys (‘a’, ‘b’, and ‘c’) and each key has a value (the value of ‘a’ is 1, ‘b’ is 2, and ‘c’ is 3). What we want to do is to write each key to its own cell in the first row of our spreadsheet. Then, what we want is each value to be found under its corresponding value key. This is what we want:

Press enter or click to view image in full size

Let’s take this step by step.

Press enter or click to view image in full size

First, we open a file ‘test_dict1.csv’ in write mode. We specify this as mode='w' but we can also simply write 'w'. If the file does not exist, one will be created. The newline='' parameter specifies that after a row is written, an extra blank row won’t be inserted. Finally, this new file is named outfile for the purpose of working with it.

Press enter or click to view image in full size

Next, we define the variable for fieldnames. This will be a list of keys that tell us how to map items from the dictionary to columns in our spreadsheet. We define them as the list: ['a', 'b', 'c'] but also notice that they are the keys of our dictionary.

Press enter or click to view image in full size

We then create an object that we call writer. This object is defined using the csv.DictWriter function which takes the csv file we named outfile and our fieldnames that we defined one line earlier as its arguments. This fieldnames parameter is required (dictionaries are unordered and so the fieldnames are a sequence of keys that specify order the values are spit out onto the rows).

Press enter or click to view image in full size

Finally, we write out all of the rows using the writerows function and we use the data from our dictionary test_dict to write the rows. Here is our result:

Our spreadsheet does not contain a header. It is just the values from our dictionary. Let’s add a header by using the writeheader() function. This function will take our fieldnames (the keys from our dictionaries) and write them to the first row.

test_dict = [{'a':1, 'b':2, 'c': 3}]
with open('test_dict2.csv', 'w', newline='') as outfile:
fieldnames = ['a', 'b', 'c']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader() # adding the header!
writer.writerows(test_dict)

Our header is now at row 1.

Press enter or click to view image in full size

Suppose we wanted to write another row. Individual rows can be written using writerow() . This function takes a dictionary with our same fieldnames as its keys.

test_dict = [{'a':1, 'b':2, 'c': 3}]
with open('test_dict3.csv', 'w', newline='') as outfile:
fieldnames = ['a', 'b', 'c']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'a': 8, 'b':7, 'c':9}) # new row!
writer.writerows(test_dict)

Result:

Press enter or click to view image in full size

Get David W. Agler’s stories in your inbox

Join Medium for free to get updates from this writer.

More data can be written with additional uses of writerows():

test_dict = [{'a':1, 'b':2, 'c': 3}]
more_data =[{'a': 99, 'c':34, 'b':33}] # More Data!
with open('test_dict3.csv', 'w', newline='') as outfile:
fieldnames = ['a', 'b', 'c']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'a': 8, 'b':7, 'c':9})
writer.writerows(test_dict)
writer.writerows(more_data) # Write more data!

Result:

Press enter or click to view image in full size

A Second Example: Missing Key-Values

Let’s look at a different example. In this case, we have a slightly larger list of dictionaries.

test_dict = [{'a':1, 'b':2, 'c': 3},
{'a': 2, 'b':6},{'c': 99, 'b': 88, }]

Notice that some dictionaries in the list have some {key:value} pairs missing. We can specify the value a missing {key:value} with the optional parameter restval. We’ll specify that if we are missing a {key:value} pair, the spreadsheet should fill in the cell with the text “MISSING”.

test_dict = [{'a':1, 'b':2, 'c': 3},
{'a': 2, 'b':6},{'c': 99, 'b': 88, }]

with open('test_dict4.csv', 'w', newline='') as outfile:
fieldnames = ['a', 'b', 'c']
writer = csv.DictWriter(outfile,
fieldnames=fieldnames, restval="MISSING") #restval!
writer.writeheader()
writer.writerows(test_dict)

Results:

Press enter or click to view image in full size

A Final Example: NBA Players

Let’s look at a more realistic example. What is the average (mean) number of years a professional basketball player plays for the national basketball association (NBA)? According to one statement made on the NBA’s website, the average (mean) is 4.5 years. Is that true? Suppose we have a list of the following dictionaries:

nba_players = 
[{'Name': 'Alaa Abdelnaby', 'Start Year': '1990', 'Last Year': '1994'},
{'Name': 'Zaid Abdul-Aziz', 'Start Year': '1968', 'Last Year': '1977'},
{'Name': 'Kareem Abdul-Jabbar', 'Start Year': '1969', 'Last Year': '1988'},
{'Name': 'Mahmoud Abdul-Rauf', 'Start Year': '1990', 'Last Year': '2000'},
{'Name': 'Tariq Abdul-Wahad', 'Start Year': '1997', 'Last Year': '2003'}]

Let’s loop through the list of dictionaries and get the keys:

for i in nba_players:
print(i.keys())

Result:

dict_keys(['Name', 'Start Year', 'Last Year'])
dict_keys(['Name', 'Start Year', 'Last Year'])
.
.

The keys of the dictionary are 'Name', 'Start Year' , and 'Last Year'. Next, create the csv file in the same manner that we did earlier.

with open('test_dict5.csv', 'w', newline='') as outfile:
fieldnames = ['Name', 'Start Year', 'Last Year']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(nba_players)

Result:

Press enter or click to view image in full size

Resources and Earlier Articles in Series

--

--

David W. Agler
David W. Agler