All Courses

Python Data Persistence - DBM Package

Vijay Mane

2 years ago

Python Data Persistence - DBM Package | insideAIML
Table of Contents
  • Introduction
  • Some of the modules of dbm packages

Introduction

          Python provides another great package named dbm package to deal with databases. This package presents a dictionary-like interface DBM style databases.
DBM stands for Database Manager. This DBM can be used by UNIX and similar to the UNIX operating system.
The dbbm package is a very simple database engine written by Ken Thompson.
These types of databases use binary encoded string objects as key, as well as value.
These databases using hashing techniques and stores data by use of a single primary key in fixed-size buckets manners which help for very fast retrieval of the data by the primary key.

Some of the modules of dbm packages

  • dbm.gnu – This module is an interface to the DBM library version as implemented by the GNU project.
  • dbm.ndbm – This module provides an interface to UNIX which makes nbdm implementation for easy.
  • dbm.dumb -This module is used as a fallback option in the event and other dbm implementations are not found. It is a useful module as this requires no external dependencies but it is slower than others.
Let’s take an example:
dbm.whichdb('InsideAIML_dbm.db')
'dbm.dumb'
import dbm

db=dbm.open('InsideAIML_dbm.db','n')
db['name']= 'InsideAIML'
db['address']='22, Raey Road, Mazgaon , Mumbai'
db['PIN']='400010'

db.close()
The open() function allows different mode for these flags which are listed below –
open() function allows different mode | insideAIML
DBM Object is a dictionary-like object similar to a shelf object. So we can perform all the dictionary operations.
This dbm objects provides get(), append(), pop() and update() methods.
Let’s take an example where we will try to open “InsideAIML_dbm” with “r” flag and run a loop over a collection of key-value pairs.
db = dbm.open('InsideAIML_dbm.db','r')
for k,v in db.items():
      print (k,v)

b'name' : b'InsideAIML'
b'address': b'22, Raey Road, Mazgaon, Mumbai'
b'PIN' : b'400010'
The dbm object is a dictionary-like object, just as a shelf object. Hence, all dictionary operations can be performed. The dbm object can invoke get(), pop(), append() and update() methods. Following code opens 'mydbm.db' with 'r' flag and iterates over collection of key-value pairs.
>>> db=dbm.open('mydbm.db','r')
>>> for k,v in db.items():
        print (k,v)

b'name' : b'Raj Deshmane'
b'address': b'Kirtinagar Pune'
b'PIN' : b'431101'
       
For more blogs/courses on data science, machine learning, artificial intelligence, and new technologies do visit us at InsideAIML.
Thanks for reading…    

Submit Review