Search code examples
pythonshelve

How to convert a shelve object into a dictionary object in Python


I have a persistent dictionary created with DB = shelve.open('Database')

This object is of type:

class 'shelve.DbfilenameShelf'

However, I want to know if it is possible to convert it back into a dictionary:

class 'dict'

PS: I know I can just use the shelve object as I would a normal dictionary, but I want to explicitly convert it from a shelve to a dictionary.


Solution

  • Just use the builtin class constructor dict:

    DB_as_dict = dict(DB)
    

    Note that this only creates a copy of the information stored in the DB, so changes to the dict will not affect the file.