Method 1: CSV Writer
To write a Python dictionary in a CSV file as a column, i.e., a single (key, value) pair per row, use the following three steps:
- Open the file in writing mode and using the
newline=''
argument to prevent blank lines. - Create a CSV writer object.
- Iterate over the (key, value) pairs of the dictionary using the
dict.items()
method. - Write one
(key, value)
tuple at a time by passing it in thewriter.writerow()
method.
Here’s the code example:
import csv # Create a dictionary of key-value pairs data = {'A':42, 'B':41, 'C':40} # Open the file in writing mode (no blank lines) with open('my_file.csv', 'w', newline='') as f: # Create a CSV writer object writer = csv.writer(f) # Write one key-value tuple per row for row in data.items(): writer.writerow(row)
Your output CSV file (column dict) looks like this:
Example 2: Vanilla Python
The shortest, most concise, and easiest way to write a dictionary as a CSV file using the dict keys as first column and the dict values as second column is to use normal Python file handling.
- First, open the file in writing mode.
- Second, iterate over all (key, value) pairs.
- Third, write each key value pair in one line using the standard Python file writing method.
Here’s the concrete example:
import csv data = {'A':42, 'B':41, 'C':40} with open('my_file.csv', 'w') as f: for key, value in data.items(): f.write(f'{key},{value}\n')
Again, the resulting CSV file (column dict) looks like this:
If you need a header in the column CSV file, you can do that with another extra call of file.write('Col_A,Col_B\n')
just before starting to iterate over the dictionary.
π Related Resource: 7 Best Ways to Convert Dict to CSV in Python
Programmer Humor
β Question: Why do programmers always mix up Halloween and Christmas?
β Answer: Because Oct 31 equals Dec 25.
(If you didn’t get this, read our articles on the oct()
and int()
Python built-in functions!)