seethesource talks about storing and loading python dictionaries from disk. his sample code was easy to read, but, after some thinking, seems incomplete (for example, the storing function assumes we’re only storing string elements to disk; there are likely unicode formatting related problems for strings; etc…).
(in my efforts to level up my python skills, i’ve been scanning blogs for python problems and solutions, to see what i can learn – i wrote this post in that context)
saving/loading objects to/from disk sounds like a very common problem to solve; python should have a library for something this common. so, before trying to write my own, more robust, version of seethesource’s code, i dug up the python documentation wiki. i was rewarded with a lesson on object pickling (pickling is pythonic for serialization?). the wiki even included a handy, relevant, example:
# Save a dictionary into a pickle file. import pickle favorite_color = { "lion": "yellow", "kitty": "red" } pickle.dump( favorite_color, open( "save.p", "wb" ) )
# Load the dictionary back from the pickle file. import pickle favorite_color = pickle.load( open( "save.p", "rb" ) ) # favorite_color is now { "lion": "yellow", "kitty": "red" }