Thursday, February 23, 2023
HomeSoftware EngineeringThe best way to Zip and Encode a Dictionary to String and...

The best way to Zip and Encode a Dictionary to String and Again in Python


When you’ve got a Python dictionary, and need to encode it as a string and zip it to save lots of area, maybe for passing a dictionary via as an atmosphere variable or comparable, then you are able to do the next

Zip then Encode / Decode then Unzip Features

import json, gzip, base64
from io import BytesIO


def _zip_then_encode(information: dict) -> str:
    """Gzip and base64 encode a dictionary"""
    if kind(information) != dict:
        increase TypeError("information should 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 may take the string and reverse it again into the dictionary as follows:

print(_decode_then_unzip(encoded_str))

Output:

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



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments