Flexible Python Red Black Tree Implementation

1.22 · active · verified Sat Apr 11

This library provides a flexible Python implementation of red-black trees, offering a low standard deviation in operation times for insertion, deletion, and lookup. It includes modules for both set-like (enforcing uniqueness) and dictionary-like use. The library is known to work across CPython 2.x, CPython 3.x, PyPy, and Jython. The current version is 1.22, with an infrequent release cadence; the last major update was in December 2023.

Warnings

Install

Imports

Quickstart

Demonstrates basic dictionary-like usage, including insertion, lookup, iteration (keys are sorted), and deletion.

from red_black_dict_mod import RedBlackTree

# Dictionary-like usage
rbd = RedBlackTree()

# Insert items
for i in range(10):
    rbd[i] = f"value_{i}"

print(f"Tree size: {len(rbd)}")
print(f"Value for key 5: {rbd[5]}")

# Check for existence
print(f"Is 7 in tree? {7 in rbd}")
print(f"Is 100 in tree? {100 in rbd}")

# Iterate through items (keys are sorted)
print("Items in sorted order:")
for k, v in rbd.items():
    print(f"  {k}: {v}")

# Delete an item
del rbd[5]
print(f"Tree size after deleting 5: {len(rbd)}")
print(f"Value for key 5 after deletion (should raise KeyError):\n")
try:
    print(rbd[5])
except KeyError as e:
    print(f"  {e}")

# Set-like usage (not directly shown in quickstart, but implied by documentation)
# The documentation states: 'A module is provided for red black trees that enforce uniqueness. 
# They allow for set-like use and dictionary-like use.'
# It's likely you would import a different module or use RedBlackTree directly for this, 
# but without clear examples, this quickstart focuses on the dictionary aspect.

view raw JSON →