[Tutor] Alternative for Shelve

Kent Johnson kent37 at tds.net
Tue May 12 12:59:19 CEST 2009


On Tue, May 12, 2009 at 4:00 AM, Timo <timomlists at gmail.com> wrote:
> Kent Johnson schreef:
>> Try the pickle module.
>
> I went from Pickle to Shelve because I couldn't store my wanted list of
> dictionaries in Pickle.

What was the problem? You should be able to create a dict whose values
are lists of dicts. This would correspond to the dict-like object you
get from shelve. Then the whole dict could be pickled. For example:

In [10]: import pickle

In [11]: d=dict()

In [12]: d[1234567] = [{'date' : '2009-05-11', 'location' :
'Germany'}, {'date' : '2009-05-04', 'location' : 'France'}]

In [13]: d[7654321] = [{'date' : '2009-03-12', 'location' :
'Belgium'}, {'date' : '2009-04-23', 'location' : 'Spain'}]

In [14]: s = pickle.dumps(d)

In [15]: s
Out[15]: "(dp0\nI7654321\n(lp1\n(dp2\nS'date'\np3\nS'2009-03-12'\np4\nsS'location'\np5\nS'Belgium'\np6\nsa(dp7\ng3\nS'2009-04-23'\np8\nsg5\nS'Spain'\np9\nsasI1234567\n(lp10\n(dp11\ng3\nS'2009-05-11'\np12\nsg5\nS'Germany'\np13\nsa(dp14\ng3\nS'2009-05-04'\np15\nsg5\nS'France'\np16\nsas."

In [16]: d2 = pickle.loads(s)

In [17]: d2
Out[17]:
{1234567: [{'date': '2009-05-11', 'location': 'Germany'},
           {'date': '2009-05-04', 'location': 'France'}],
 7654321: [{'date': '2009-03-12', 'location': 'Belgium'},
           {'date': '2009-04-23', 'location': 'Spain'}]}

Kent


More information about the Tutor mailing list