[Tutor] output of dictionaries
Karl Pflästerer
sigurd at 12move.de
Tue May 10 19:00:30 CEST 2005
On 10 Mai 2005, tomcloyd at bestmindhealth.com wrote:
> I'm creating a small database using a dictionary of dictionaries, and I
> want to output it to a file. It seems that only strings can be output to
> files, and I cannot quite figure out how to quickly and simply convert my
> dictionary to a list of strings or whatever. Or maybe I'm going about this
> all wrong.
> So, the most general form of my question: how can I store a dictionary
> containing some data records stored as dictionaries - a dictionary of
> dictionaries - in a file, so I can read it back in later and process its
> contents?
You could use the pickle module to serialize and deserialize your data.
Here's an example (very simple):
. >>> import pickle
. >>> d
. {1: {2: 3, 3: 4}, 2: {2: 3, 3: 4}, 3: {2: 3, 3: 4}}
. >>> f = open("test.pickle", "w")
. >>> pickle.dump(d, f)
. >>> f.close()
. >>> f = open("test.pickle")
. >>> d2 = pickle.load(f)
. >>> f.close()
. >>> d2 == d
. True
Or take a look at the shelve module; it could be just what you want.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list