How to Zip and Encode a Dictionary to String and Back in Python

If you have a Python dictionary, and wish to encode it as a string and zip it to conserve area, maybe for passing a dictionary through as an environment variable or comparable, then you can do the following

Zip then Encode/ Decode then Unzip Functions

 import json, gzip, base64
from io import BytesIO


def _ zip_then_encode( information: dict) -> > str:
""" Gzip and base64 encode a dictionary""".
if type( information)!= dict:.
raise 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()). translate(" ascii").

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

To utilize the encode and translate functions, you can do the following:

Zip and Encode the Dictionary to String

 my_dict = {
' somekey': {
' another': 'worth'.
}
}

encoded_str = _ zip_then_encode( my_dict).
print( encoded_str).

Output:

H4sIAM0O9mMC/6tWKs7PTc1OrVSyUqhWSszLL8lILQKylcoSc0pTlWprAUha5+ ghAAAA

Decode and Unzip the String to Dictionary

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

 print( _ decode_then_unzip( encoded_str)).

Output:

{'somekey': {'another': 'worth'}}

.

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: