15.4. CSV DictWriter

  • Writes iterable of dicts (eg. list[dict]) to CSV file

  • csv.DictWriter()

  • Remember to add mode='w' to open() function

  • Default 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': 'Blackthorn', '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,Blackthorn,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': 'Blackthorn', '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","Blackthorn","31"
"Carol","Corn","32"
"Dave","Durian","33"
"Eve","Elderberry","34"
"Mallory","Melon","15"

15.4.4. Assignments

# %% About
# - Name: CSV DictWriter ListMappings
# - Difficulty: easy
# - Lines: 5
# - 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. Write `DATA` to `FILE` in CSV format
# 2. Use `csv.DictWriter()`
# 3. Sort header (fieldnames)
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do `FILE` w formacie CSV
# 2. Użyj `csv.DictWriter()`
# 3. Posortuj nagłówek (fieldnames)
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# age,firstname,lastname
# 30,Alice,Apricot
# 31,Bob,Blackthorn
# 32,Carol,Corn
# 33,Dave,Durian
# 34,Eve,Elderberry
# 15,Mallory,Melon
# <BLANKLINE>

# %% Hints
# - `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,Blackthorn
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 -f -v myfile.py`

# %% Imports
import csv

# %% Types

# %% Data
FILE = r'_temporary.csv'

DATA = [
    {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
    {'firstname': 'Bob', 'lastname': 'Blackthorn', '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 ListObjects
# - Difficulty: easy
# - Lines: 6
# - 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. Write `DATA` to `FILE` in CSV format
# 2. Use `csv.DictWriter()`
# 3. Sort header (fieldnames)
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zapisz `DATA` do `FILE` w formacie CSV
# 2. Użyj `csv.DictWriter()`
# 3. Posortuj nagłówek (fieldnames)
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# age,firstname,lastname
# 30,Alice,Apricot
# 31,Bob,Blackthorn
# 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,Blackthorn
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 -f -v myfile.py`

# %% Imports
import csv

# %% Types

# %% Data
FILE = r'_temporary.csv'

class User:
    def __init__(self, firstname, lastname, age=None):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age

    def __repr__(self):
        clsname = self.__class__.__qualname__
        arguments = ', '.join(f'{k}={v!r}' for k,v in vars(self).items())
        return f'{clsname}({arguments})'


DATA = [
    User('Alice', 'Apricot', age=30),
    User('Bob', 'Blackthorn', 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='wt', encoding='utf-8') as file:
    ...