shelve object back to dictionary
Fredrik Lundh
fredrik at pythonware.com
Thu Oct 6 11:55:12 EDT 2005
Ryan Krauss wrote:
> Is there an easy way to convert a shelved object back to a dictionary?
> When I save a dictionary using shelve and then load it in a later
> session, I have an object whose property names are the keys of the
> dictionary used as an input to shelve. For example, instead of
> user['name'] I have user.name. I would prefer to have the scripts I
> write to analyze the saved data have a similar syntax to the ones I
> used to create it, so I would rather deal with a dictionary after I
> load the shelved data.
session 1:
>>> import shelve
>>> db = shelve.open("foo")
>>> d = {"a": 1, "b": 2}
>>> db["key"] = d
>>> print d
{'a': 1, 'b': 2}
>>> print db["key"]
{'a': 1, 'b': 2}
>>> db.close()
session 2:
>>> import shelve
>>> db = shelve.open("foo")
>>> db["key"]
{'a': 1, 'b': 2}
>>> type(db["key"])
<type 'dict'>
>>> db["key"].key
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'dict' object has no attribute 'key'
>>>
are you sure you're saving dictionaries? what does "print type(obj)" print
for objects from your shelve? what does the following print for your data-
base ?
>>> import anydbm
>>> db = anydbm.open("<insert shelve name here>")
>>> db[db.keys()[0]]
</F>
More information about the Python-list
mailing list