HomeSoftware EngineeringTips on how to Zip and Encode a Dictionary to String and...

Tips on how to Zip and Encode a Dictionary to String and Again in Python


When you’ve got a Python dictionary, and wish to encode it as a string and zip it to avoid wasting house, maybe for passing a dictionary by way of as an setting variable or comparable, then you are able to do the next

import os, json, gzip, sys, base64, logging
from io import BytesIO


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

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

To make use of the encode and decode capabilities, 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)
print(encoded_str)

Output:

H4sIAM0O9mMC/6tWKs7PTc1OrVSyUqhWSszLL8lILQKylcoSc0pTlWprAUha5+ghAAAA

Decode and Unzip the String to Dictionary

Now you’ll be able to take the string and reverse it again into the dictionary as follows:

print(_decode_then_unzip(encoded_str))

Output:

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

RELATED ARTICLES

Most Popular

Recent Comments