13.3. Pickle Dump

  • pickle.dump(object) -> file

  • pickle.dumps(object) -> bytes

13.3.1. SetUp

>>> import pickle

13.3.2. Sequence

>>> DATA = ('Alice', 'Apricot', 30)
>>>
>>> pickle.dumps(DATA)
b'\x80\x04\x95\x17\x00\x00\x00\x00\x00\x00\x00\x8c\x05Alice\x94\x8c\x07Apricot\x94K\x1e\x87\x94.'

13.3.3. List of Sequences

>>> DATA = [
...     ('firstname', 'lastname', 'age'),
...     ('Alice', 'Apricot', 30),
...     ('Bob', 'Blackthorn', 31),
...     ('Carol', 'Corn', 32),
...     ('Dave', 'Durian', 33),
...     ('Eve', 'Elderberry', 34),
...     ('Mallory', 'Melon', 15),
... ]
>>>
>>> pickle.dumps(DATA)
b'\x80\x04\x95\xa5\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\tfirstname\x94\x8c\x08lastname\x94\x8c\x03age\x94\x87\x94\x8c\x05Alice\x94\x8c\x07Apricot\x94K\x1e\x87\x94\x8c\x03Bob\x94\x8c\nBlackthorn\x94K\x1f\x87\x94\x8c\x05Carol\x94\x8c\x04Corn\x94K \x87\x94\x8c\x04Dave\x94\x8c\x06Durian\x94K!\x87\x94\x8c\x03Eve\x94\x8c\nElderberry\x94K"\x87\x94\x8c\x07Mallory\x94\x8c\x05Melon\x94K\x0f\x87\x94e.'

13.3.4. Mapping

>>> DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
>>>
>>> pickle.dumps(DATA)
b'\x80\x04\x956\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\tfirstname\x94\x8c\x05Alice\x94\x8c\x08lastname\x94\x8c\x07Apricot\x94\x8c\x03age\x94K\x1eu.'

13.3.5. List of Mappings

>>> 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},
... ]
>>>
>>> pickle.dumps(DATA)
b'\x80\x04\x95\xcd\x00\x00\x00\x00\x00\x00\x00]\x94(}\x94(\x8c\tfirstname\x94\x8c\x05Alice\x94\x8c\x08lastname\x94\x8c\x07Apricot\x94\x8c\x03age\x94K\x1eu}\x94(h\x02\x8c\x03Bob\x94h\x04\x8c\nBlackthorn\x94h\x06K\x1fu}\x94(h\x02\x8c\x05Carol\x94h\x04\x8c\x04Corn\x94h\x06K u}\x94(h\x02\x8c\x04Dave\x94h\x04\x8c\x06Durian\x94h\x06K!u}\x94(h\x02\x8c\x03Eve\x94h\x04\x8c\nElderberry\x94h\x06K"u}\x94(h\x02\x8c\x07Mallory\x94h\x04\x8c\x05Melon\x94h\x06K\x0fue.'

13.3.6. 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', 'Blackthorn', age=31),
...     User('Carol', 'Corn', age=32),
...     User('Dave', 'Durian', age=33),
...     User('Eve', 'Elderberry', age=34),
...     User('Mallory', 'Melon', age=15),
... ]
>>>
>>> pickle.dumps(DATA)
b'\x80\x04\x95\x03\x01\x00\x00\x00\x00\x00\x00]\x94(\x8c\x08__main__\x94\x8c\x04User\x94\x93\x94)\x81\x94}\x94(\x8c\tfirstname\x94\x8c\x05Alice\x94\x8c\x08lastname\x94\x8c\x07Apricot\x94\x8c\x03age\x94K\x1eubh\x03)\x81\x94}\x94(h\x06\x8c\x03Bob\x94h\x08\x8c\nBlackthorn\x94h\nK\x1fubh\x03)\x81\x94}\x94(h\x06\x8c\x05Carol\x94h\x08\x8c\x04Corn\x94h\nK ubh\x03)\x81\x94}\x94(h\x06\x8c\x04Dave\x94h\x08\x8c\x06Durian\x94h\nK!ubh\x03)\x81\x94}\x94(h\x06\x8c\x03Eve\x94h\x08\x8c\nElderberry\x94h\nK"ubh\x03)\x81\x94}\x94(h\x06\x8c\x07Mallory\x94h\x08\x8c\x05Melon\x94h\nK\x0fube.'

13.3.7. To File

  • open(file, mode='wb') for writing binary data

SetUp:

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

Solution:

>>> with open('/tmp/myfile.pkl', mode='wb') as file:
...     pickle.dump(DATA, file)

Result:

>>> open('/tmp/myfile.pkl', mode='rb').read()
b'\x80\x04\x95\xcd\x00\x00\x00\x00\x00\x00\x00]\x94(}\x94(\x8c\tfirstname\x94\x8c\x05Alice\x94\x8c\x08lastname\x94\x8c\x07Apricot\x94\x8c\x03age\x94K\x1eu}\x94(h\x02\x8c\x03Bob\x94h\x04\x8c\nBlackthorn\x94h\x06K\x1fu}\x94(h\x02\x8c\x05Carol\x94h\x04\x8c\x04Corn\x94h\x06K u}\x94(h\x02\x8c\x04Dave\x94h\x04\x8c\x06Durian\x94h\x06K!u}\x94(h\x02\x8c\x03Eve\x94h\x04\x8c\nElderberry\x94h\x06K"u}\x94(h\x02\x8c\x07Mallory\x94h\x04\x8c\x05Melon\x94h\x06K\x0fue.'

13.3.8. Recap

  • pickle.dump(object) -> file

  • pickle.dumps(object) -> bytes

  • open(file, mode='wb') for writing binary data

13.3.9. Assignments

# %% About
# - Name: Pickle Dump Tuple
# - Difficulty: easy
# - Lines: 1
# - 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 `result: bytes` with serialized `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bytes` z serializowanym `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# ('Alice', 'Apricot', 30)

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

>>> result = pickle.loads(result)

>>> assert type(result) is tuple, \
'Variable `result` has invalid type, should be tuple'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
('Alice', 'Apricot', 30)
"""

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

# %% Types
result: bytes

# %% Data
DATA = ('Alice', 'Apricot', 30)

# %% Result
result = ...

# %% About
# - Name: Pickle Dump ListTuple
# - Difficulty: easy
# - Lines: 1
# - 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 `result: bytes` with serialized `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bytes` z serializowanym `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [('firstname', 'lastname', 'age'),
#  ('Alice', 'Apricot', 30),
#  ('Bob', 'Blackthorn', 31),
#  ('Carol', 'Corn', 32),
#  ('Dave', 'Durian', 33),
#  ('Eve', 'Elderberry', 34),
#  ('Mallory', 'Melon', 15)]

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

>>> result = pickle.loads(result)

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is tuple for row in result), \
'Variable `result` has invalid type, should be tuple'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[('firstname', 'lastname', 'age'),
 ('Alice', 'Apricot', 30),
 ('Bob', 'Blackthorn', 31),
 ('Carol', 'Corn', 32),
 ('Dave', 'Durian', 33),
 ('Eve', 'Elderberry', 34),
 ('Mallory', 'Melon', 15)]
"""

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

# %% Types
result: bytes

# %% Data
DATA = [
    ('firstname', 'lastname', 'age'),
    ('Alice', 'Apricot', 30),
    ('Bob', 'Blackthorn', 31),
    ('Carol', 'Corn', 32),
    ('Dave', 'Durian', 33),
    ('Eve', 'Elderberry', 34),
    ('Mallory', 'Melon', 15),
]

# %% Result
result = ...

# %% About
# - Name: Pickle Dump Dict
# - Difficulty: easy
# - Lines: 1
# - 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 `result: bytes` with serialized `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bytes` z serializowanym `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

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

>>> result = pickle.loads(result)

>>> assert type(result) is dict, \
'Variable `result` has invalid type, should be dict'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
{'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}
"""

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

# %% Types
result: bytes

# %% Data
DATA = {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}

# %% Result
result = ...

# %% About
# - Name: Pickle Dump ListDict
# - Difficulty: easy
# - Lines: 1
# - 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 `result: bytes` with serialized `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bytes` z serializowanym `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [{'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}]

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

>>> result = pickle.loads(result)

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is dict for row in result), \
'Variable `result` has invalid type, should be dict'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[{'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}]
"""

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

# %% Types
result: bytes

# %% 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},
]

# %% Result
result = ...

# %% About
# - Name: Pickle Dump ListObject
# - Difficulty: easy
# - Lines: 1
# - 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 `result: bytes` with serialized `DATA`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bytes` z serializowanym `DATA`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [User(firstname='Alice', lastname='Apricot', age=30),
#  User(firstname='Bob', lastname='Blackthorn', age=31),
#  User(firstname='Carol', lastname='Corn', age=32),
#  User(firstname='Dave', lastname='Durian', age=33),
#  User(firstname='Eve', lastname='Elderberry', age=34),
#  User(firstname='Mallory', lastname='Melon', age=15)]

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

>>> result = pickle.loads(result)

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is User for row in result), \
'Variable `result` has invalid type, should be User'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[User(firstname='Alice', lastname='Apricot', age=30),
 User(firstname='Bob', lastname='Blackthorn', age=31),
 User(firstname='Carol', lastname='Corn', age=32),
 User(firstname='Dave', lastname='Durian', age=33),
 User(firstname='Eve', lastname='Elderberry', age=34),
 User(firstname='Mallory', lastname='Melon', age=15)]
"""

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

# %% Types
result: bytes

# %% Data
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
result = ...

# %% About
# - Name: Pickle Dump ToFile
# - Difficulty: easy
# - Lines: 2
# - 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. Serialize `DATA` to `FILE`
# 2. Use `pickle` module
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zserializuj `DATA` do `FILE`
# 2. Użyj modułu `pickle`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Example
# >>> result
# [{'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}]

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

>>> with open(FILE, mode='rb') as file:
...     result = pickle.load(file)

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

>>> assert type(result) is list, \
'Variable `result` has invalid type, should be list'

>>> assert all(type(row) is dict for row in result), \
'Variable `result` has invalid type, should be dict'

>>> from pprint import pprint
>>> pprint(result, width=79, sort_dicts=False)
[{'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}]
"""

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

# %% Types

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

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