Monday, November 18, 2024
HomeSoftware EngineeringHow you can Zip and Encode a Dictionary to String and Again...

How you can Zip and Encode a Dictionary to String and Again in Python


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 Features

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:
        increase TypeError("knowledge have to be a dictionary")
    compressed = BytesIO()
    with gzip.GzipFile(fileobj=compressed, mode="w") as f:
        json_response = json.dumps(knowledge)
        f.write(json_response.encode("utf-8"))
    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 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 possibly can 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