Question

I have a short shelve practice program that runs as expected in python 2.7. I moved it over to 3.3, as such:

import shelve

db = shelve.open('lib')
db['a'] = "string1"
db['b'] = "string2"
keylist = db.keys()
print( keylist )
db.close()

Now I get this result (not exactly an error, but not the desired behavior:

KeysView(<shelve.DbfilenameShelf object at 0x7f0f06b3be90>)

Any ideas on what is going wrong and how to fix it? Did something change in shelve for 3.3?

Was it helpful?

Solution

shelve is meant to behave like a dict which has changed... In Python 2.x dict's use to return a list when .keys() was called, in Python 3.x it returns a view object of the keys. If you want the actual keys, you have to materialise them to a list:

keylist = list(db.keys())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top