SqliteDict

2.1.0 · active · verified Sat Apr 11

SqliteDict is a Python library that provides a persistent dictionary interface, backed by sqlite3 and using pickle for serialization. It is designed to be multithread-safe as a workaround for Python's `sqlite3` thread limitations and supports multiple tables within a single database file. It offers a simple, Pythonic dict-like interface to an SQLite database, currently at version 2.1.0, and is actively maintained.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create and interact with an SqliteDict, covering both `autocommit=True` and manual `commit()` usage, as well as the recommended `with` statement for proper database closing. It stores dictionary objects that are automatically pickled.

from sqlitedict import SqliteDict
import os

db_path = 'my_data.sqlite'

# Clean up previous run if exists
if os.path.exists(db_path):
    os.remove(db_path)

# Open a new SqliteDict with autocommit enabled (recommended for many small writes)
with SqliteDict(db_path, autocommit=True) as db:
    db['user:1'] = {'name': 'Alice', 'age': 30}
    db['user:2'] = {'name': 'Bob', 'age': 25}
    db['settings:theme'] = 'dark'
    print(f"Added 3 items. Current length: {len(db)}")

# Re-open the database (autocommit defaults to False if not specified)
with SqliteDict(db_path) as db_read_only:
    print(f"Retrieved user:1: {db_read_only['user:1']}")
    print(f"All keys: {list(db_read_only.keys())}")

    # Manual commit is needed if autocommit is False
    db_read_only['new_item'] = 'This will NOT be saved without commit()'
    # db_read_only.commit() # Uncomment to save

print("Demonstrating explicit commit")
# Open without autocommit, requiring explicit commit
with SqliteDict(db_path, autocommit=False) as db_manual:
    db_manual['product:101'] = {'name': 'Widget', 'price': 19.99}
    db_manual.commit() # Explicitly commit changes
    print(f"Added product:101. Current length: {len(db_manual)}")

# Verify the manually committed item
with SqliteDict(db_path) as db_verify:
    print(f"Retrieved product:101: {db_verify['product:101']}")

# Clean up the database file
if os.path.exists(db_path):
    os.remove(db_path)

view raw JSON →