Python Shelve Module

From the Python 3 documentation

A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.

Save variables

import shelve

wife = ['Pretty', 'Lovely', 'Nice']
# Open shelf file and save data
with shelve.open('mydata') as shelf_file:
    shelf_file['wife'] = wife

Open and read variables

# Open shelf file and read data
with shelve.open('mydata') as shelf_file:
    print(type(shelf_file))
    # Access stored value by key
    print(shelf_file['wife'])
<class 'shelve.DbfilenameShelf'>
['Pretty', 'Lovely', 'Nice']

Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the list() function to get them in list form.

# Access all keys and values in shelf
with shelve.open('mydata') as shelf_file:
    print(list(shelf_file.keys()))
    print(list(shelf_file.values()))
['wife']
[['Pretty', 'Lovely', 'Nice']]