[Tutor] Shelve: remove dictionary from list

Kent Johnson kent37 at tds.net
Tue Mar 3 19:36:05 CET 2009


On Tue, Mar 3, 2009 at 12:18 PM, Timo <timomlists at gmail.com> wrote:
> Hello all, I'm using the Shelve module to store dictionaries in a list as a
> value of a key.
>
> So:
>
> key = [{'keyA' : 1, 'keyB' : 2}, {'key1' : 1, 'key2' : 2}]
>
> The problem is I can't remove a dictionary from the list.
>
>
> import shelve
>
> s = shelve.open('file')
> try:
>   for index, value in enumerate(s['key']):
>       if value['keyA'] == 1 and value['keyB'] == 2:
>           del value[index]
> finally:
>   s.close()
>
>
> If I do some printing in between, I can see the dictionary actually gets
> removed, but doesn't get saved. Any ideas why?

>From the shelve docs:
By default, mutations to persistent-dictionary mutable entries are not
automatically written back. If the optional writeback parameter is set
to True, all entries accessed are cached in memory, and written back
at close time; this can make it handier to mutate mutable entries in
the persistent dictionary, but, if many entries are accessed, it can
consume vast amounts of memory for the cache, and it can make the
close operation very slow since all accessed entries are written back
(there is no way to determine which accessed entries are mutable, nor
which ones were actually mutated).

In other words, by default, shelve does not know about changes you
make to mutable values. You can either
- open the shelve with writeback=True
- explicitly store the modified value back into the shelve:
  key = s['key']
  # modify key
  s['key'] = key
  s.close()

Kent


More information about the Tutor mailing list