Shelve - How to Shelve Files with Python - Example

Here are some brief examples of how to us shelve to store objects in python. Note this differs to pickle by the needs to store the data to a key.

Shelve Example 1 - Creating a Shelve Database


import shelve

s = shelve.open('test.db')
    s['key'] = {'apple': 23, 'cherry': 56, 'pear': 33}

Shelve Example 2 - Accessing a Shelve Database

import shelve

s = shelve.open('test.db')
s['key'] = {'apple': 23, 'cherry': 56, 'pear': 33}
s.close()


r = shelve.open('test.db')
print (r['key'])
r.close()
Returns:
{'apple': 23, 'cherry': 56, 'pear': 33}