Trie Prefix Search And Autocomplete (Python)

Build a trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.

PythonData Fetching

Code

pythonsnippet
37 lines
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False
        self.freq = 0


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word, freq=1):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_word = True
        node.freq += freq

    def suggest(self, prefix, limit=5):
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)
            if not node:
                return []
        results = []

        def dfs(n, path):
            if n.is_word:
                results.append((path, n.freq))
            for ch, child in n.children.items():
                dfs(child, path + ch)

        dfs(node, prefix)
        results.sort(key=lambda x: -x[1])
        return [w for w, _ in results[:limit]]

How it works

Count the classes TrieNode and Trie and the functions __init__, insert, suggest and dfs as the entire surface area of Trie Prefix Search And Autocomplete (Python).

Iteration happens inside for ch in word — everything outside it runs once.

A fresh value is allocated for the result; the arguments stay untouched.

Using it

The primary signature is def insert(self, word, freq=1)

insert is the public entry point; everything else in the file exists to support it.

Key statements

def insert(self, word, freq=1):
    node = self.root
    for ch in word:
        if ch not in node.children:
            node.children[ch] = TrieNode()
        node = node.children[ch]
    node.is_word = True
    node.freq += freq
def __init__(self):
    self.children = {}
    self.is_word = False
    self.freq = 0
def __init__(self):
    self.root = TrieNode()

Interactive Tools for This Topic

FAQ

Does `insert` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `__init__`, `insert`, `suggest` at load time.