Back
+20 XP
Concept

Embedded Key-Value Storage with dbm

The standard `dbm` module provides lightweight, disk-persisted key-value storage. Keys and values are stored as raw bytes and manipulated just like a standard Python dictionary 🗝️.

python
import dbm, tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    db_path = f"{tmp_dir}/store"

    # Open DB for reading and writing ('c' = create if not exist):
    with dbm.open(db_path, "c") as db:
        db["session_101"] = "user_ada"

    with dbm.open(db_path, "r") as db:
        print(f"Read key: {db['session_101'].decode()} 🗝️")

# 23. Embedded Key-Value Storage with dbm The standard `dbm` module provides lightweight, disk-persisted key-value storage. Keys and values are stored as raw bytes and manipulated just like a standard Python dictionary 🗝️. ```python import dbm, tempfile with tempfile.TemporaryDirectory() as tmp_dir: db_path = f"{tmp_dir}/store" # Open DB for reading and writing ('c' = create if not exist): with dbm.open(db_path, "c") as db: db["session_101"] = "user_ada" with dbm.open(db_path, "r") as db: print(f"Read key: {db['session_101'].decode()} 🗝️") ``` When you need persistence for session keys or URL mappings but don't need the relational queries of SQLite, `dbm` is the fastest built-in tool! 🗝️ --- ### Question What data types are strictly required for keys and values when using the `dbm` module? 🧠 - [ ] a. Strings or raw bytes 🗝️ - [ ] b. Arbitrary Python objects like lambdas and functions - [ ] c. JSON strings only - [ ] d. Floating point numbers only --- ### Challenge Import `dbm` and `tempfile`. In a temp directory, open `dbm.open(path, 'c')`. Write `db['status'] = 'online'`. Reopen in read mode and print the decoded string value. 🎯 <details> <summary>Solution</summary> ```python import dbm, tempfile with tempfile.TemporaryDirectory() as td: path = f"{td}/test_kv" with dbm.open(path, "c") as db: db["status"] = "online" with dbm.open(path, "r") as db: print(db["status"].decode()) ``` </details>

Checkpoint

What data types are strictly required for keys and values when using the `dbm` module? 🧠

Practice

Import `dbm` and `tempfile`. In a temp directory, open `dbm.open(path, 'c')`. Write `db['status'] = 'online'`. Reopen in read mode and print the decoded string value. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks