I'm relatively new to and encoding and decoding, in fact I don't have any experience with it at all.
I was wondering, how would I decode a dictionary in Python 3 into an unreadable format that would prevent someone from modifying it outside the program?
Likewise, how would I then read from that file and encode the dictionary back?
My test code right now only writes to and reads from a plain text file.
import ast
myDict = {}
#Writer
fileModifier = open('file.txt', 'w')
fileModifier.write(str(myDict)))
fileModifier.close()
#Reader
fileModifier = open('file.txt', 'r')
myDict = ast.literal_eval(fileModifier.read())
fileModifier.close()
The typical thing to use here is either the
json
orpickle
modules (both in the standard library). The process is called "serialization".pickle
can serialize almost arbitrary python objects whereasjson
can only serialize basic types/objects (integers, floats, strings, lists, dictionaries).json
is human readible at the end of the day whereaspickle
files aren't.An alternative to encoding/decoding is to simply use a file as a
dict
, and python has theshelve
module which does exactly this. This module uses a file as database and provide adict
-like interface to it.It has some limitations, for example keys must be strings, and it's obviously slower than a normal
dict
since it performs I/O operations.Depending on what your dictionary is holding you can use an encoding library like json or pickle (useful for storing my complex python data structures).
Here is an example using json, to use pickle just replace all instances of
json
withpickle
and you should be good to go.