SQLTrie

0.11.2 · active · verified Sat Apr 11

SQLTrie is a Python library that implements a SQL-based prefix tree (trie) data structure, drawing inspiration from `pygtrie` and `python-diskcache`. It enables efficient storage and retrieval of key-value pairs where keys are sequences (e.g., strings) and operations like prefix-based lookups are optimized. The current version, 0.11.2, was released in February 2025. Given its 'Development Status :: 1 - Planning', the release cadence is irregular and the API is evolving.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates common `SQLTrie` operations, including storing and retrieving values by key, checking key existence, and iterating over items with a given prefix. It highlights the use of a context manager for proper database handling and implicitly showcases data persistence in the SQLite backend.

import os
from sqltrie import Trie

db_path = 'my_sqltrie.db'

# Ensure a clean slate for the example
if os.path.exists(db_path):
    os.remove(db_path)

# Initialize a SQLTrie instance, typically taking a filename for SQLite storage.
# Using a context manager ensures proper closing and data persistence.
with Trie(filename=db_path) as trie:
    trie["apple"] = 100
    trie["apricot"] = 200
    trie["banana"] = 300
    trie["bandana"] = 400
    trie["applepie"] = 50

    print(f"Value for 'apple': {trie['apple']}")
    print(f"'banana' exists: {'banana' in trie}")
    print(f"'grape' exists: {'grape' in trie}")

    print("\nItems with prefix 'ap':")
    for key, value in trie.items(prefix="ap"):
        print(f"  {key}: {value}")

    print("\nAll items:")
    for key, value in trie.items():
        print(f"  {key}: {value}")

# Data is persisted after exiting the 'with' block.
# To verify, load the trie again from the same file.
with Trie(filename=db_path) as loaded_trie:
    print(f"\nValue for 'apricot' after reload: {loaded_trie['apricot']}")
    print(f"'applepie' exists after reload: {'applepie' in loaded_trie}")

# Clean up the database file
os.remove(db_path)
print(f"\nCleaned up database file '{db_path}'.")

view raw JSON →