Python Glossary Русский

Python 3.14+compression.zstdfunction

compression.zstd.train_dict()

dictionaries

Trains a zstd dictionary on samples of typical data. A dictionary sharply improves compression of many small similar records.

Syntax

compression.zstd.train_dict(samples, dict_size) -> ZstdDict

A dictionary pays off for small objects (hundreds of bytes to a few KiB): a short JSON record may even grow when compressed without one. You need many samples; with just a couple training fails with ZstdError. The dictionary becomes part of your format: store it and pass the same zstd_dict to decompress, or the data cannot be restored.

Examples

# Python 3.14+
from compression import zstd  # → ? нужна сборка CPython с libzstd
samples = [f'{{"id": {i}, "name": "user{i}", "active": true}}'.encode() for i in range(200)]
zd = zstd.train_dict(samples, 1024)
one = samples[5]
print(len(zstd.compress(one)) > len(one))  # → True — без словаря стало больше
packed = zstd.compress(one, zstd_dict=zd)
print(len(packed) < len(one))  # → True
try:
    zstd.decompress(packed)
except zstd.ZstdError as e:
    print(e)  # → Unable to decompress Zstandard data: Dictionary mismatch

See also

Open in the full glossarydocs.python.orgReport an inaccuracy