dbm
The Python dbm module provides a generic dictionary-like interface to DBM-style databases, enabling persistent key-value storage backed by a file on disk.
Here’s a quick look at storing and retrieving values:
>>> import dbm
>>> with dbm.open("greetings", "c") as db:
... db["hello"] = "world"
... db["foo"] = "bar"
...
>>> with dbm.open("greetings", "r") as db:
... db["hello"]
...
b'world'
Key Features
- Provides a
dict-like interface for persisting key-value pairs in a file-backed database - Automatically selects the best available backend (
dbm.sqlite3,dbm.gnu,dbm.ndbm, ordbm.dumb) - Stores keys and values as
bytes, automatically encoding any string input - Supports the
inoperator and methods such as.keys(),.get(),.setdefault(), and.clear() - Integrates with Python’s context manager protocol for safe file handling
- Serves as the underlying storage engine for the
shelvemodule
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
dbm.open() |
Function | Opens or creates a database file and returns a database object |
dbm.whichdb() |
Function | Identifies which backend module should be used to open a given database file |
dbm.error |
Exception | Base exception for DBM errors; also a tuple of all backend-specific exception types |
dbm.sqlite3 |
Module | SQLite-backed implementation available in Python 3.13 and later |
dbm.gnu |
Module | GNU GDBM-backed implementation for Unix systems |
dbm.dumb |
Module | Pure-Python fallback used when no other backend is available |
Examples
Using .get() to read a value with a fallback default:
>>> import dbm
>>> with dbm.open("cache", "c") as db:
... db["visits"] = "0"
...
>>> with dbm.open("cache", "r") as db:
... db.get("visits", b"not found")
... db.get("missing", b"not found")
...
b'0'
b'not found'
Checking for key existence and listing all keys:
>>> import dbm
>>> with dbm.open("items", "c") as db:
... db["x"] = "alpha"
... db["y"] = "beta"
...
>>> with dbm.open("items", "r") as db:
... b"x" in db
... db.keys()
...
True
[b'x', b'y']
Using whichdb() to discover which backend opened a file — the output varies by platform and available backends:
>>> import dbm
>>> with dbm.open("cache", "c") as db:
... db["k"] = "v"
...
>>> dbm.whichdb("cache")
'dbm.sqlite3'
Common Use Cases
The most common tasks for dbm include:
- Caching computed results or downloaded content between program runs
- Storing application configuration or session state as string key-value pairs
- Building lightweight lookup tables that persist across invocations
- Serving as the storage layer for
shelvewhen persisting arbitrary Python objects
Real-World Example
The following script uses dbm to persist a simple application configuration, initializing missing keys with defaults on first run and then reading them back:
config_store.py
import dbm
CONFIG_FILE = "app_config"
defaults = {
"host": "localhost",
"port": "8080",
"debug": "false",
}
with dbm.open(CONFIG_FILE, "c") as config:
for key, value in defaults.items():
config.setdefault(key, value)
with dbm.open(CONFIG_FILE, "r") as config:
for key in config.keys():
print(key.decode(), "=", config[key].decode())
Run it:
$ python config_store.py
host = localhost
port = 8080
debug = false
The .setdefault() method writes each default only if the key is absent, so re-running the script after manually changing a value leaves the changed setting intact.
Related Resources
Tutorial
Data Management With Python, SQLite, and SQLAlchemy
In this tutorial, you'll learn how to store and retrieve data using Python, SQLite, and SQLAlchemy as well as with flat files. Using SQLite with Python brings with it the additional benefit of accessing data with SQL. By adding SQLAlchemy, you can work with data in terms of objects and methods.
For additional information on related topics, take a look at the following resources:
- TinyDB: A Lightweight JSON Database for Small Projects (Tutorial)
- The Python pickle Module: How to Persist Objects in Python (Tutorial)
- Bytes Objects: Handling Binary Data in Python (Tutorial)
- Caching in Python Using the LRU Cache Strategy (Tutorial)
- SQLite and SQLAlchemy in Python: Move Your Data Beyond Flat Files (Course)
- TinyDB: A Lightweight JSON Database for Small Projects (Quiz)
- Serializing Objects With the Python pickle Module (Course)
- Python Bytes (Quiz)
- Caching in Python With lru_cache (Course)
By Leodanis Pozo Ramos • Updated March 25, 2026