[Tutor] How do I save a dictionary to disk? (another newbie question)

Kirby Urner urnerk@qwest.net
Thu, 10 Jan 2002 23:19:02 -0800


>
>
>try:
>   f=open("test.txt","r")
            ^^^^^^^^
            oops, I called it output.txt above.

I like the shelve option mentioned by PV, but be forewarned
that a shelved dictionary doesn't have all the functionality
of a real dictionary.

Here's some playing around with that object:

Create a shelve object, populate it, close it, and
remove it from the module:

   >>> import shelve
   >>> d= shelve.open("text.sh")
   >>> d['a']=10
   >>> d['b']=90
   >>> d.close()
   >>> del d

Reopen as newd, check it for contents:

   >>> newd = shelve.open("text.sh")
   >>> newd
   <shelve.DbfilenameShelf instance at 0x01884BA0>
   >>> newd.items()
   Traceback (most recent call last):
     File "<pyshell#154>", line 1, in ?
       newd.items()
   AttributeError: DbfilenameShelf instance has
   no attribute 'items'

Not as powerful as a real dictionary!

   >>> newd.keys()  # OK, good, the keys are there
   ['b', 'a']
   >>> newd.values
   Traceback (most recent call last):
   File "<pyshell#156>", line 1, in ?
       newd.values
   AttributeError: DbfilenameShelf instance has no attribute 'values'

Yeah well, we can get 'em one at a time.

Compare what a shelve dictionary gives you, versus a real
dictionary:

   >>> dir(newd)
   ['__del__', '__delitem__', '__doc__', '__getitem__',
   '__init__',   '__len__', '__module__', '__setitem__',
   'close', 'dict', 'get', 'has_key', 'keys', 'sync']

   >>> dir({})
   ['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__',
   '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
   '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
   '__ne__', '__new__', '__reduce__', '__repr__', '__setattr__',
   '__setitem__', '__str__', 'clear', 'copy', 'get', 'has_key', 'items',
   'iteritems', 'iterkeys', 'itervalues', 'keys', 'popitem', 'setdefault',
   'update', 'values']

I still think just writing a human readable file, and
parsing that back in as a dictionary, is probably the best
thing.  You never know when you might want the same info in
some other program (not even Python).  Text is way more
universal than some pickle or anydbm format.

Kirby