In some small python applications, when you do not need a relational database, you can easily use a persistent dictionary to store name-value pairs, which is very similar to the python dictionary, the main difference is data... in some small python applications, you can easily use persistent dictionaries to store name/value pairs without the need for relational databases. it is very similar to the python dictionary, the main difference is that data is read and written on the disk. Another difference is that the dbm key and value must be of the string type.
1. select dbm module
Python supports many dbm modules. Unfortunately, the files created by each dbm module are not compatible.
The following table lists these modules:
Module description
Dbm selects the best dbm module
Dbm. dumb uses a simple but portable implementation of the dbm database
Dbm. gnu uses the GNU dbm Library
Generally, the dbm module is used unless a dbm database has special advanced functions.
2. create a permanent dictionary
Import dbmdb = dbm. open ('bookmark', 'C') # Add option db ['myblog'] = 'jonathanlife .sinaapp.com 'print (db ['myblog']) # save and disable db. close ()
There are three ways for open functions to open dbm:
Flag usage
C open the file to read and write it, and create the file if necessary
W open the file and read and write it. if the file does not exist, it will not be created
N open the file for read and write, but always create a new blank file
You can also pass an optional parameter indicating the mode. this mode saves a set of UNIX file permissions.
3. access the persistent Dictionary
Objects returned from the open function are treated as dictionary objects. The access method for the value is as follows:
Db ['key'] = 'value' value = db ['key'] # delete value: del db ['key'] # traverse all keys: for key in db. keys (): # your code here
Code example:
import dbm#open existing filedb = dbm.open('websites', 'w')#add itemdb['first_data'] = 'Hello world' #verify the previous item remainsif db['first_data'] != None: print('the data exists')else: print('Missing item') #iterate over the keys, may be slowfor key in db.keys(): print("Key=",key," value=",db[key]) #delete itemdel db['first_data'] #close and save to diskdb.close()