pygtrie: Pure Python Trie Data Structure

2.5.0 · active · verified Mon Apr 06

pygtrie is a pure Python library implementing a trie data structure. It provides `Trie`, `CharTrie`, and `StringTrie` classes, each implementing a mutable mapping (dictionary-like) interface. Its strengths lie in prefix-based operations, such as iterating over or deleting subtries, prefix checking, and shortest/longest prefix look-ups. It also includes a `PrefixSet` for managing sets of prefixes. The current version is 2.5.0, with releases occurring periodically to introduce features and address compatibility.

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `Trie` for key-value storage and `StringTrie` for path-like keys, including prefix-based retrieval.

from pygtrie import Trie, StringTrie

t = Trie()
t['foo'] = 1
t['bar'] = 2
t['baz'] = 3
t['foobar'] = 4

print(f"Trie contains 'foo': {t['foo']}")
print(f"All items with prefix 'foo': {list(t.items('foo'))}")

s_trie = StringTrie(separator='/')
s_trie['/home/user/docs/report.pdf'] = 'Report 2023'
s_trie['/home/user/photos/vacation.jpg'] = 'Vacation Pics'

print(f"StringTrie for '/home/user/docs': {list(s_trie.keys('/home/user/docs'))}")

view raw JSON →