Wednesday, February 22, 2023
HomeSoftware EngineeringEasy methods to Zip and Encode a Dictionary to String and Again...

Easy methods to Zip and Encode a Dictionary to String and Again in Python


In case you have a Python dictionary, and wish to encode it as a string and zip it to avoid wasting house, maybe for passing a dictionary by means of as an atmosphere 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 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)

# H4sIAM0O9mMC/6tWKs7PTc1OrVSyUqhWSszLL8lILQKylcoSc0pTlWprAUha5+ghAAAA

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

Decode and Unzip the String to Dictionary

print(_decode_then_unzip(encoded_str))

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments