If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
If I have a dictionary full of nested stuff, how do I store that in a database, as a string? and then, convert it back to a dictionary when I'm ready to parse?
Edit: I just want to convert it to a string...and then back to a dictionary.
Why don't you use some serialization/deserialization from pickle module ?
Options:
1) Pickling
2) XML
3) JSON
others I am sure. It has a lot to do on how much portability means to you.
Best, under your stated conditions:
import cPickle
...
thestring = cPickle.dumps(thedict, -1)
the -1
ensures the most efficient serialization and produces a binary string (arbitrary string of bytes). If you need an ascii string (because e.g. some Unicode transcoding is going to happen and you can't switch the field's type from, say, TEXT
to BLOB
), avoid the -1
, but you'll then be less efficient.
To get the dict back later from the string, in either case,
thenewdict = cPickle.loads(thestring)
You have two options
use a standard serialization format (json, xml, yaml, ...)
use cPickle:
There are any number of serialization methods out there, JSON is readable, reasonably compact, supported natively, and portable. I prefer it over pickle, since the latter can execute arbitrary code and potentially introduce security holes, and because of its portability.
Depending on your data's layout, you may also be able to use your ORM to directly map the data into database constructs.