Zip & Encode Dict to String & Again in Python

If in case you have a Python dictionary, and need to encode it as a string and zip it to avoid wasting area, maybe for passing a dictionary via as an surroundings variable or comparable, then you are able to do the next

Zip then Encode / Decode then Unzip Capabilities

import json, gzip, base64
from io import BytesIO

def _zip_then_encode(knowledge: dict) -> str:
    """Gzip and base64 encode a dictionary"""
    if sort(knowledge) != dict:
        elevate TypeError("knowledge should be a dictionary")
    compressed = BytesIO()
    with gzip.GzipFile(fileobj=compressed, mode="w") as f:
        json_response = json.dumps(knowledge)
    return base64.b64encode(compressed.getvalue()).decode("ascii")

def _decode_then_unzip(knowledge) -> dict:
    res = base64.b64decode(knowledge)
    res = gzip.decompress(res)
    res = res.decode("utf-8")
    res = json.masses(res)
    return res

To make use of the encode and decode features, you are able to do the next:

Zip and Encode the Dictionary to String

my_dict = {
    'somekey': {
        'one other': 'worth'

encoded_str = _zip_then_encode(my_dict)



Decode and Unzip the String to Dictionary

Now you possibly can take the string and reverse it again into the dictionary as follows:



{'somekey': {'one other': 'worth'}}

Leave a Reply

Your email address will not be published. Required fields are marked *