Shelve: add data to the database and recover them

Add data

It is very easy to add data to a database with shelve. In fact when we create the database we create a dictionary and to add a key and a value is all we have to do. If you know how to use a dictionary in Python, is all you have to know. The only difference is that the dictionary and the keys will be stored ina  db file at our dispousal.

This is the code to add a data (key) to the database:

"""Create a database

Create a db and add a record, then close it
"""

import shelve

s = shelve.open("db3.db")

s["Mario Rossi"] = [6,5,7]

s.close()

When you will open the file again. If you check for the record like this:

import shelve

s = shelve.open("db3.db")

for k in s:
	print(k, s[k])

s.close()

The output will be:

Mario Rossi [6, 5, 7]
>>>

Video

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.