12.2. Serialization Dump

  • dump(object) -> file

  • dumps(object) -> str

12.2.1. Sequence

>>> DATA = ('Alice', 'Apricot', 30)
>>>
>>> def dumps(data, fieldseparator=','):
...     row = tuple(str(x) for x in DATA)
...     return fieldseparator.join(row)
>>>
>>> dumps(DATA)
'Alice,Apricot,30'

12.2.2. Mapping

>>> DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
>>>
>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = tuple(DATA.keys())
...     row = tuple(DATA.values())
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.append(fieldseparator.join(str(x) for x in row))
...     return recordseparator.join(records)
>>>
>>> dumps(DATA)
'firstname,lastname,age;Alice,Apricot,30'

12.2.3. List of Sequence

>>> DATA = [
...     ('firstname', 'lastname', 'age'),
...     ('Alice', 'Apricot', 30),
...     ('Bob', 'Banana', 31),
...     ('Carol', 'Corn', 32),
...     ('Dave', 'Durian', 33),
...     ('Eve', 'Elderberry', 34),
...     ('Mallory', 'Melon', 15),
... ]
>>>
>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = tuple(DATA[0])
...     rows = tuple(DATA[1:])
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.extend(fieldseparator.join(str(x) for x in row) for row in rows)
...     return recordseparator.join(records)
>>>
>>> dumps(DATA)
'firstname,lastname,age;Alice,Apricot,30;Bob,Banana,31;Carol,Corn,32;Dave,Durian,33;Eve,Elderberry,34;Mallory,Melon,15'

12.2.4. List of Mappings

>>> 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},
... ]
>>>
>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = sorted(set(key for row in DATA for key in row.keys()))
...     rows = [tuple(row.get(x,'') for x in header) for row in DATA]
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.extend(fieldseparator.join(str(x) for x in row) for row in rows)
...     return recordseparator.join(records)
>>>
>>> dumps(DATA)
'age,firstname,lastname;30,Alice,Apricot;31,Bob,Banana;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'

12.2.5. List of Objects

  • vars() will convert object to dict

>>> class User:
...     def __init__(self, firstname, lastname, age):
...         self.firstname = firstname
...         self.lastname = lastname
...         self.age = age
...
...     def __repr__(self):
...         clsname = self.__class__.__name__
...         firstname = self.firstname
...         lastname = self.lastname
...         age = self.age
...         return f'{clsname}({firstname=}, {lastname=}, {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),
... ]
>>>
>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = sorted(set(key for row in DATA for key in vars(row).keys()))
...     rows = [tuple(vars(row).get(x,'') for x in header) for row in DATA]
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.extend(fieldseparator.join(str(x) for x in row) for row in rows)
...     return recordseparator.join(records)
>>>
>>> dumps(DATA)
'age,firstname,lastname;30,Alice,Apricot;31,Bob,Banana;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon'

12.2.6. To File

SetUp:

>>> 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},
... ]

Solution:

>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = sorted(set(key for row in DATA for key in row.keys()))
...     rows = [tuple(row.get(x,'') for x in header) for row in DATA]
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.extend(fieldseparator.join(str(x) for x in row) for row in rows)
...     return recordseparator.join(records)
>>>
>>> def dump(data, file):
...      to_write = dumps(data, fieldseparator=',', recordseparator=';') + '\n'
...      with open(file, mode='wt', encoding='utf-8') as file:
...          file.write(to_write)
>>>
>>>
>>> dump(DATA, '/tmp/myfile.dat')

Result:

>>> open('/tmp/myfile.dat').read()
'age,firstname,lastname;30,Alice,Apricot;31,Bob,Banana;32,Carol,Corn;33,Dave,Durian;34,Eve,Elderberry;15,Mallory,Melon\n'

12.2.7. Use Case - 1

SetUp:

>>> DATA = [
...     ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
...     (5.8, 2.7, 5.1, 1.9, 'virginica'),
...     (5.1, 3.5, 1.4, 0.2, 'setosa'),
...     (5.7, 2.8, 4.1, 1.3, 'versicolor'),
...     (6.3, 2.9, 5.6, 1.8, 'virginica'),
...     (6.4, 3.2, 4.5, 1.5, 'versicolor'),
...     (4.7, 3.2, 1.3, 0.2, 'setosa'),
...     (7.0, 3.2, 4.7, 1.4, 'versicolor'),
...     (7.6, 3.0, 6.6, 2.1, 'virginica'),
...     (4.6, 3.1, 1.5, 0.2, 'setosa'),
... ]

Usage:

>>> def dumps(data, fieldseparator=',', recordseparator=';'):
...     header = tuple(DATA[0])
...     rows = tuple(DATA[1:])
...     records = []
...     records.append(fieldseparator.join(str(x) for x in header))
...     records.extend(fieldseparator.join(str(x) for x in row) for row in rows)
...     return recordseparator.join(records)
>>>
>>>
>>> dumps(DATA)
'sepal_length,sepal_width,petal_length,petal_width,species;5.8,2.7,5.1,1.9,virginica;5.1,3.5,1.4,0.2,setosa;5.7,2.8,4.1,1.3,versicolor;6.3,2.9,5.6,1.8,virginica;6.4,3.2,4.5,1.5,versicolor;4.7,3.2,1.3,0.2,setosa;7.0,3.2,4.7,1.4,versicolor;7.6,3.0,6.6,2.1,virginica;4.6,3.1,1.5,0.2,setosa'

12.2.8. Use Case - 2

SetUp:

>>> from pprint import pprint
>>>
>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>> DATA = User('Mark', 'Watney')

Usage:

>>> def dumps(data):
...     values = vars(data).values()
...     result = ','.join(values) + '\n'
...     return result
>>>
>>> result = dumps(DATA)
>>>
>>> pprint(result)
'Mark,Watney\n'

12.2.9. Use Case - 3

>>> from pprint import pprint
>>>
>>> class User:
...     def __init__(self, firstname, lastname):
...         self.firstname = firstname
...         self.lastname = lastname
>>>
>>> DATA = [
...     User('Mark', 'Watney'),
...     User('Melissa', 'Lewis'),
...     User('Rick', 'Martinez'),
... ]

Usage:

>>> def dumps(data):
...     values = [','.join(vars(row).values()) for row in data]
...     result = '\n'.join(values) + '\n'
...     return result
>>>
>>> result = dumps(DATA)
>>>
>>> pprint(result)
'Mark,Watney\nMelissa,Lewis\nRick,Martinez\n'

12.2.10. Use Case - 4

SetUp:

>>> DATA = [
...     ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
...     (5.8, 2.7, 5.1, 1.9, 'virginica'),
...     (5.1, 3.5, 1.4, 0.2, 'setosa'),
...     (5.7, 2.8, 4.1, 1.3, 'versicolor'),
...     (6.3, 2.9, 5.6, 1.8, 'virginica'),
...     (6.4, 3.2, 4.5, 1.5, 'versicolor'),
...     (4.7, 3.2, 1.3, 0.2, 'setosa'),
...     (7.0, 3.2, 4.7, 1.4, 'versicolor'),
...     (7.6, 3.0, 6.6, 2.1, 'virginica'),
...     (4.6, 3.1, 1.5, 0.2, 'setosa'),
... ]

Solution:

>>> def dump(data, file):
...     values = [','.join(map(str, row)) for row in data]
...     result = '\n'.join(values) + '\n'
...     with open(file, mode='wt') as file:
...         file.write(result)
>>>
>>> dump(DATA, file='/tmp/myfile.csv')

Result:

>>> result = open('/tmp/myfile.csv').read()
>>> print(result)
sepal_length,sepal_width,petal_length,petal_width,species
5.8,2.7,5.1,1.9,virginica
5.1,3.5,1.4,0.2,setosa
5.7,2.8,4.1,1.3,versicolor
6.3,2.9,5.6,1.8,virginica
6.4,3.2,4.5,1.5,versicolor
4.7,3.2,1.3,0.2,setosa
7.0,3.2,4.7,1.4,versicolor
7.6,3.0,6.6,2.1,virginica
4.6,3.1,1.5,0.2,setosa

12.2.11. Assignments

# %% About
# - Name: Serialization Dumps Sequence
# - 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. Define function `dumps()`, which serializes Sequence:
#    - Argument: `data: tuple`
#    - Returns: `str`
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `;`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje Sequence:
#    - Argument: `data: tuple`
#    - Zwraca: `str`
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `;`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# Mark,Watney,41

# %% Hints
# - `[x for x in data]`
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
Mark,Watney,41
"""

# %% 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

# %% Types
from typing import Callable
type data = tuple[str,str,int]
dumps: Callable[[data], str]
result: str

# %% Data
DATA = ('Mark', 'Watney', 41)

# %% Result
def dumps(data):
    ...

result = ...

# %% About
# - Name: Serialization Dumps Mapping
# - 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. Define function `dumps()`, which serializes Mapping:
#    - Argument: `data: dict`
#    - Returns: `str`
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje Mapping:
#    - Argument: `data: dict`
#    - Zwraca: `str`
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# firstname,lastname,age
# Mark,Watney,41

# %% Hints
# - `[x for x in data]`
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
firstname,lastname,age
Mark,Watney,41
"""

# %% 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

# %% Types
from typing import Callable
type data = dict[str,str|int]
dumps: Callable[[data], str]
result: str

# %% Data
DATA = {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41}

# %% Result
def dumps(data):
    ...

result = ...

# %% About
# - Name: Serialization Dumps ListSequence
# - Difficulty: medium
# - 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. Define function `dumps()`, which serializes list[Sequence]:
#    - Argument: `data: list[tuple]`
#    - Returns: `str`
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje list[Sequence]:
#    - Argument: `data: list[tuple]`
#    - Zwraca: `str`
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# firstname,lastname,age
# Mark,Watney,41
# Melissa,Lewis,40
# Rick,Martinez,39
# Alex,Vogel,40
# Chris,Beck,36
# Beth,Johanssen,29

# %% Hints
# - `[x for x in data]`
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
firstname,lastname,age
Mark,Watney,41
Melissa,Lewis,40
Rick,Martinez,39
Alex,Vogel,40
Chris,Beck,36
Beth,Johanssen,29
"""

# %% 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

# %% Types
from typing import Callable
type data = list[tuple[str,str,int]]
dumps: Callable[[data], str]
result: str

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Mark', 'Watney', 41),
    ('Melissa', 'Lewis', 40),
    ('Rick', 'Martinez', 39),
    ('Alex', 'Vogel', 40),
    ('Chris', 'Beck', 36),
    ('Beth', 'Johanssen', 29),
]

# %% Result
def dumps(data):
    ...

result = ...

# %% About
# - Name: Serialization Dumps ListMapping
# - Difficulty: medium
# - Lines: 18
# - Minutes: 13

# %% 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. Define function `dumps()`, which serializes list[Mapping]:
#    - Argument: `data: list[dict]`
#    - Returns: `str`
#    - First line is a header
#    - Sort header
#    - Mind, that values must be in appropriate columns (according to header)
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje list[Mapping]:
#    - Argument: `data: list[dict]`
#    - Zwraca: `str`
#    - Pierwsza linia to nagłówek
#    - Posortuj nagłówek
#    - Zwróć uwagę, aby wartości były w odpowiednich kolumnach (wg. nagłówka)
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# age,firstname,lastname
# 41,Mark,Watney
# 40,Melissa,Lewis
# 39,Rick,Martinez
# 40,Alex,Vogel
# 36,Chris,Beck
# 29,Beth,Johanssen

# %% Hints
# - `str.join()`
# - `dict.keys()`
# - `dict.values()`
# - `[x for x in data]`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
age,firstname,lastname
41,Mark,Watney
40,Melissa,Lewis
39,Rick,Martinez
40,Alex,Vogel
36,Chris,Beck
29,Beth,Johanssen
"""

# %% 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

# %% Types
from typing import Callable
type data = list[dict[str,str|int]]
dumps: Callable[[data], str]
result: str

# %% Data
DATA = [
    {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41},
    {'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 40},
    {'firstname': 'Rick', 'lastname': 'Martinez', 'age': 39},
    {'firstname': 'Alex', 'lastname': 'Vogel', 'age': 40},
    {'firstname': 'Chris', 'lastname': 'Beck', 'age': 36},
    {'firstname': 'Beth', 'lastname': 'Johanssen', 'age': 29},
]

# %% Result
def dumps(data):
    ...

result = ...

# %% About
# - Name: Serialization Dumps ListObjects
# - Difficulty: medium
# - Lines: 18
# - Minutes: 13

# %% 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. Define function `dumps()`, which serializes list[object]:
#    - Argument: `data: list[object]`
#    - Returns: `str`
#    - First line is a header
#    - Sort header
#    - Mind, that values must be in appropriate columns (according to header)
# 2. Define `result: str` with result of `dumps()` function for `DATA`
# 3. Non-functional requirements:
#    - Do not use `import` and any module
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dumps()`, która serializuje list[object]:
#    - Argument: `data: list[object]`
#    - Zwraca: `str`
#    - Pierwsza linia to nagłówek
#    - Posortuj nagłówek
#    - Zwróć uwagę, aby wartości były w odpowiednich kolumnach (wg. nagłówka)
# 2. Zdefiniuj `result: str` z wynikiem funkcji `dumps()` dla `DATA`
# 3. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `\n`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# age,firstname,lastname
# 41,Mark,Watney
# 40,Melissa,Lewis
# 39,Rick,Martinez
# 40,Alex,Vogel
# 36,Chris,Beck
# 29,Beth,Johanssen

# %% Hints
# - `str.join()`
# - `dict.keys()`
# - `dict.values()`
# - `[x for x in data]`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> print(result)
age,firstname,lastname
41,Mark,Watney
40,Melissa,Lewis
39,Rick,Martinez
40,Alex,Vogel
36,Chris,Beck
29,Beth,Johanssen
"""

# %% 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

# %% Types
from typing import Callable
type data = list[object]
dumps: Callable[[data], str]
result: str

# %% Data
class User:
    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname = lastname
        self.age = age

    def __repr__(self):
        clsname = self.__class__.__name__
        firstname = self.firstname
        lastname = self.lastname
        age = self.age
        return f'{clsname}({firstname=}, {lastname=}, {age=})'


DATA = [
    User('Mark', 'Watney', age=41),
    User('Melissa', 'Lewis', age=40),
    User('Rick', 'Martinez', age=39),
    User('Alex', 'Vogel', age=40),
    User('Chris', 'Beck', age=36),
    User('Beth', 'Johanssen', age=29),
]

# %% Result
def dumps(data):
    ...

result = ...

# %% About
# - Name: Serialization Dump ListMapping
# - Difficulty: easy
# - Lines: 4
# - Minutes: 2

# %% 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. Define function `dump()`, which serializes list[dict] to file:
#    - Argument: `data: list[dict]`, `file: str`
#    - Returns: `None`
# 2. Non-functional requirements:
#    - Do not use `import` and any module
#    - Do not convert numbers to `int` or `float`, leave them as `str`
#    - Quoting: none
#    - Delimiter: `,`
#    - Lineseparator: `;`
#    - File ends with an empty line
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `dump()`, która serializuje list[dict] do pliku:
#    - Argument: `data: list[dict]`, `file: str`
#    - Zwraca: `None`
# 2. Wymagania niefunkcjonalne:
#    - Nie używaj `import` ani żadnych modułów
#    - Nie konwertuj liczb do `int` lub `float`, pozostaw je jako `str`
#    - Quoting: żadne
#    - Delimiter: `,`
#    - Lineseparator: `;`
#    - Plik kończy się pustą linią
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# age,firstname,lastname
# 41,Mark,Watney
# 40,Melissa,Lewis
# 39,Rick,Martinez
# 40,Alex,Vogel
# 36,Chris,Beck
# 29,Beth,Johanssen
# <BLANKLINE>

# %% Hints
# - `tuple()`
# - `dict.keys()`
# - `dict.values()`
# - `list.append()`
# - `list.extend()`
# - `str.join()`

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 12), \
'Python 3.12+ required'

>>> dump(DATA, file=FILE)
>>> result = open(FILE).read()

>>> from os import remove
>>> remove(FILE)

>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> assert result != '', \
'File content is empty'

>>> print(result)
age,firstname,lastname
41,Mark,Watney
40,Melissa,Lewis
39,Rick,Martinez
40,Alex,Vogel
36,Chris,Beck
29,Beth,Johanssen
<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

# %% Types
from typing import Callable
type data = list[dict[str,str|int]]
dump: Callable[[data], None]

# %% Data
FILE = '_temporary.csv'

DATA = [
    {'firstname': 'Mark', 'lastname': 'Watney', 'age': 41},
    {'firstname': 'Melissa', 'lastname': 'Lewis', 'age': 40},
    {'firstname': 'Rick', 'lastname': 'Martinez', 'age': 39},
    {'firstname': 'Alex', 'lastname': 'Vogel', 'age': 40},
    {'firstname': 'Chris', 'lastname': 'Beck', 'age': 36},
    {'firstname': 'Beth', 'lastname': 'Johanssen', 'age': 29},
]

def ascsv(sequece):
    return ','.join(str(x) for x in sequece)

def dumps(data):
    header = sorted(set(key for row in data for key in row.keys()))
    rows = [tuple(row.get(x,'') for x in header) for row in data]
    lines = []
    lines.append(ascsv(header))
    lines.extend(ascsv(row) for row in rows)
    return '\n'.join(lines)

# %% Result
def dump(data, file):
    ...