Creating Persistent Dictionaries

All of the DBM modules support an open function to create a new dbm object. Once opened, you can store data in the dictionary, read data, close the dbm object (and the associated data file or files), remove items, and test for the existence of a key in the dictionary.

To open a DBM persistent dictionary, use the open function on the module you choose. For example, you can create a persistent dictionary with the anydbm module.

Try It Out Creating a Persistent Dictionary

Enter the following code and name your file dbmcreate.py:

import anydbm db = anydbm.open('websites', 'c')

db['www.python.org'] = 'Python home page' print db['www.python.org']

When you run this script, you'll see output like the following:

$ python dbmcreate.py Python home page

How It Works

This example uses the recommended anydbm module.

The open function requires the name of the dictionary to create. This name gets translated into the name of the data file or files that may already be on the disk. (The DBM module may — though not always — create more than one file, usually a file for the data and one for the index of the keys.) The name of the dictionary is treated as a base filename, including the path. Usually, the underlying DBM library will append a suffix such as .dat for data. You can find the file yourself by looking for the file named websites, most likely in your current working directory.

You should also pass the optional flag. This flag is not optional for the dbhash module. The following table lists the available flags.

Flag

Usage

c

Opens the data file for reading and writing, creating the file if needed.

n

Opens the file for reading and writing, but always creates a new empty file. If one already exists, it will be overwritten and its contents lost.

w

Opens the file for reading and writing, but if the file doesn't exist it will not be created.

You can also pass another optional parameter, the mode. The mode holds a set of Unix file permissions. See Chapter 8 for more on opening files.

The open method of the dbm modules returns a new dbm object, which you can then use to store and retrieve data.

After you open a persistent dictionary, you can write values as you normally would with Python dictionaries, as shown in the following example:

Both the key and the value must be strings and can't be other objects, like numbers or python objects. Remember, however, that if you want to save an object, you can serialize it using the pickle module, as you saw in Chapter 8.

The close method closes the file or files and saves the data to disk.

Was this article helpful?

0 0

Post a comment