15.4. CSV DictWriter
Writes iterable of dicts (eg. list[dict]) to CSV file
csv.DictWriter()
Remember to add
mode='w'
toopen()
functionDefault encoding is
encoding='utf-8'
15.4.1. SetUp
>>> import csv
15.4.2. Minimal
Data:
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Banana', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
... {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
... {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
... ]
Usage:
>>> fieldnames = DATA[0].keys()
>>>
>>> with open('/tmp/myfile.csv', mode='wt') as file:
... result = csv.DictWriter(file, fieldnames)
... result.writeheader()
... result.writerows(DATA)
24
Result:
>>> print(open('/tmp/myfile.csv').read())
firstname,lastname,age
Alice,Apricot,30
Bob,Banana,31
Carol,Corn,32
Dave,Durian,33
Eve,Elderberry,34
Mallory,Melon,15
15.4.3. Parametrized
Data:
>>> DATA = [
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Banana', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
... {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
... {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
... ]
Usage:
>>> fieldnames = DATA[0].keys()
>>>
>>> with open('/tmp/myfile.csv', mode='wt', encoding='utf-8') as file:
... result = csv.DictWriter(file, fieldnames, delimiter=',', quoting=csv.QUOTE_ALL, quotechar='"', lineterminator='\n')
... result.writeheader()
... result.writerows(DATA)
29
Result:
>>> print(open('/tmp/myfile.csv').read())
"firstname","lastname","age"
"Alice","Apricot","30"
"Bob","Banana","31"
"Carol","Corn","32"
"Dave","Durian","33"
"Eve","Elderberry","34"
"Mallory","Melon","15"
15.4.4. Assignments
# %% About
# - Name: CSV DictWriter Fixed
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Using `csv.DictWriter()` save `DATA` to `FILE`
# 2. Open file in your spreadsheet program like:
# Microsoft Excel, Libre Office or Numbers etc.
# 3. Open file in simple in your IDE and simple text editor like:
# Notepad, vim, gedit
# 4. Non functional requirements:
# - All fields must be enclosed by double quote `"` character
# - Use `,` to separate columns
# - Use Unix `\n` line terminator
# 5. Run doctests - all must succeed
# %% Polish
# 1. Za pomocą `csv.DictWriter()` zapisz `DATA` do `FILE`
# 2. Spróbuj otworzyć plik w arkuszu kalkulacyjnym tj.
# Microsoft Excel, Libre Office lub Numbers itp
# 3. Spróbuj otworzyć plik w IDE i prostym edytorze tekstu tj.
# Notepad, vim lub gedit
# 4. Wymagania niefunkcjonalne:
# - Wszystkie pola muszą być otoczone znakiem cudzysłowu `"`
# - Użyj `,` do oddzielenia kolumn
# - Użyj zakończenia linii Unix `\n`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# "firstname","lastname","age"
# "Alice","Apricot","30"
# "Bob","Banana","31"
# "Carol","Corn","32"
# "Dave","Durian","33"
# "Eve","Elderberry","34"
# "Mallory","Melon","15"
# <BLANKLINE>
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> result = open(FILE).read()
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> from os import remove
>>> remove(FILE)
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
"firstname","lastname","age"
"Alice","Apricot","30"
"Bob","Banana","31"
"Carol","Corn","32"
"Dave","Durian","33"
"Eve","Elderberry","34"
"Mallory","Melon","15"
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.csv'
DATA = [
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
{'firstname': 'Bob', 'lastname': 'Banana', 'age': 31},
{'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
{'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
{'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
{'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
]
# %% Result
with open(FILE, mode='wt', encoding='utf-8') as file:
...
# %% About
# - Name: CSV DictWriter Objects
# - Difficulty: medium
# - Lines: 6
# - Minutes: 8
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Using `csv.DictWriter()` save data to `FILE`
# 2. Non-functional requirements:
# - Use `,` to separate columns
# - Use `utf-8` encoding
# - Use Unix `\n` line terminator
# - sort header (fieldnames)
# 3. Run doctests - all must succeed
# %% Polish
# 1. Za pomocą `csv.DictWriter()` zapisz dane do `FILE`
# 2. Wymagania niefunkcjonalne:
# - Użyj `,` do oddzielenia kolumn
# - Użyj kodowania `utf-8`
# - Użyj zakończenia linii Unix `\n`
# - posortuj nagłówek (fieldnames)
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Example
# >>> result
# age,firstname,lastname
# 30,Alice,Apricot
# 31,Bob,Banana
# 32,Carol,Corn
# 33,Dave,Durian
# 34,Eve,Elderberry
# 15,Mallory,Melon
# <BLANKLINE>
# %% Hints
# - `vars()`
# - `sorted()`
# - `dict.keys()`
# - `csv.DictWriter()`
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> result = open(FILE).read()
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> from os import remove
>>> remove(FILE)
>>> print(result)
age,firstname,lastname
30,Alice,Apricot
31,Bob,Banana
32,Carol,Corn
33,Dave,Durian
34,Eve,Elderberry
15,Mallory,Melon
<BLANKLINE>
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
import csv
# %% Types
# %% Data
FILE = r'_temporary.txt'
class User:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
DATA = [
User('Alice', 'Apricot', age=30),
User('Bob', 'Banana', age=31),
User('Carol', 'Corn', age=32),
User('Dave', 'Durian', age=33),
User('Eve', 'Elderberry', age=34),
User('Mallory', 'Melon', age=15),
]
# %% Result
with open(FILE, mode='w', encoding='utf-8') as file:
...