moving from perl - multidimensional arrays

Andrew Dalke adalke at mindspring.com
Tue Dec 10 16:59:19 EST 2002


Vince Skahan wrote:
> I'm trying to recode an existing project from perl5 to Python
> pretty much as an excuse to do something 'real' in python to
> learn the differences etc. and ran into a roadblock.  How do
> you store a python structure to disk ?

Look at the pickle module.


 >>> info = {
...     "name": "list-l",
...
... }
 >>> class ListInfo:
...     def __init__(self, name, description, count, moderators):
...             self.name = name
...             self.description = description
...             self.count = count
...             self.moderators = moderators
...
 >>> data = {}
 >>> def add(info):
...     data[info.name] = info
...
 >>> add(ListInfo("testlist1", "test list one", 1234, "dude1 at foo.com 
dude2 at bar.com dude3 at baz.com".split()))
 >>> add(ListInfo("testlist2", "test list two", 2345, "dude4 at foo.com 
dude4 at bar.com dude5 at baz.com".split()))
 >>>
 >>> data
{'testlist1': <__main__.ListInfo instance at 0x810c5ac>, 'testlist2': 
<__main__.ListInfo instance at 0x8156794>}
 >>> import pickle
 >>> outfile = open("save.info", "wb")
 >>> pickle.dump(data, outfile)
 >>> outfile.close()
 >>> infile = open("save.info", "rb")
 >>> data2 = pickle.load(infile)
 >>> print data2
{'testlist1': <__main__.ListInfo instance at 0x816d034>, 'testlist2': 
<__main__.ListInfo instance at 0x815438c>}
 >>> data2["testlist1"].description
'test list one'
 >>>

See also marshal, the various DBMs, and ZODB for other solutions.
A combination of pickles and DBM works pretty well.

					Andrew





More information about the Python-list mailing list