Skip to content

Instantly share code, notes, and snippets.

@nick3499
Created November 2, 2021 22:45
Show Gist options
  • Save nick3499/468af495219d0be1ffd575e1d81e4878 to your computer and use it in GitHub Desktop.
Save nick3499/468af495219d0be1ffd575e1d81e4878 to your computer and use it in GitHub Desktop.
Pickle Test: dict(), pickle, unpickle, serialize, deserialize, with open()
import pickle
example_dict = {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7'}
with open('dict_pickle', 'wb') as pickle_out:
pickle.dump(example_dict, pickle_out)
print('\x1b[32mPrint pickled or serialized dictionary:\x1b[0m\n')
with open('/home/nick/Desktop/dict_pickle', 'rb') as file_out:
print(f'{file_out.read()}\n')
with open('dict_pickle', 'rb') as pickle_in:
example_dict_load = pickle.load(pickle_in)
print('\x1b[32mPrint unpickled or deserialized dictionary:\x1b[0m\n')
print(f'{example_dict_load}\n')
print('\x1b[32mPrint values from dictionary:\x1b[0m\n')
print(f"\x1b[33mexample_dict_load['one']\x1b[0m --> {example_dict_load['one']}")
print(f"\x1b[33mexample_dict_load['two']\x1b[0m --> {example_dict_load['two']}")
print(f"\x1b[33mexample_dict_load['three']\x1b[0m --> {example_dict_load['three']}")
@nick3499
Copy link
Author

nick3499 commented Nov 2, 2021

Print pickled or serialized dictionary:

b'\x80\x04\x95Q\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x03one\x94\x8c\x011\x94\x8c\x03two\x94\x8c\x012\x94\x8c\x05three\x94\x8c\x013\x94\x8c\x04four\x94\x8c\x014\x94\x8c\x04five\x94\x8c\x015\x94\x8c\x03six\x94\x8c\x016\x94\x8c\x05seven\x94\x8c\x017\x94u.'

Print unpickled or deserialized dictionary:

{'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7'}

Print values from dictionary:

example_dict_load['one'] --> 1
example_dict_load['two'] --> 2
example_dict_load['three'] --> 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment