Last active
September 19, 2020 15:20
-
-
Save GDBSD/7846b21229211ed112ed5a0da868013e to your computer and use it in GitHub Desktop.
Compress and decompress a Python dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import gzip | |
| import json | |
| source_dict = { | |
| "New Year's Day": "Fri, Jan 1, 2021", | |
| "Martin Luther King Jr. Day": "Mon, Jan 18, 2021", | |
| "Washington's Birthday": "Mon, Feb 15, 2021", | |
| "Arbor Day": "Fri, Apr 30, 2021", | |
| "Memorial Day": "Mon, May 31, 2021", | |
| "Independence Day": "Mon, Jul 5, 2021", | |
| "Labor Day": "Mon, Sep 6, 2021", | |
| "Columbus Day": "Mon, Oct 11, 2021", | |
| "Veterans Day": "Thu, Nov 11, 2021", | |
| "Thanksgiving": "Thu, Nov 25, 2021", | |
| "Christmas Day": "Fri, Dec 24, 2021", | |
| "New Year's Eve": "Fri, Dec 31, 2021" | |
| } | |
| def compress_dict(source): | |
| """Compress a Python dictionary | |
| :param source: object - Python dict | |
| :return: object - gzip | |
| """ | |
| # Convert the dictionary to json so we can pickle it. | |
| json_data = json.dumps(source, indent=2) | |
| # Convert to bytes and compress | |
| encoded_obj = json_data.encode('utf-8') | |
| # Zip it | |
| comp_data = gzip.compress(encoded_obj) | |
| return comp_data | |
| def uncompress_dict(gzip_file): | |
| """Uncompress a gzipped json file and decode it into a Python dictionary, | |
| :param gzip_file: | |
| :return: Python dictionary | |
| """ | |
| unzipped = gzip.decompress(gzip_file) | |
| decoded_json = json.loads(unzipped) | |
| return decoded_json | |
| if __name__ == '__main__': | |
| zipped_dict = compress_dict(source_dict) | |
| uncompressed_dict = uncompress_dict(zipped_dict) | |
| for k, v in uncompressed_dict.items(): | |
| print(f'{k} is {v}') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment