Code Snippets
/

Trie Implementation in Python

Trie Implementation in Python

A trie (prefix tree) stores strings character-by-character so prefix queries run in O(length) instead of O(N * length). The Pythonic shape uses a dict of dicts plus a sentinel key for 'word ends here'. This entry covers the dict-of-dicts trie, a class-based variant with explicit nodes, and the autocomplete query you build it for.

Python
Medium
3 snippets
trie
trie-operations
data-structures
py-standard-library

697 views

21

END = '__end__'

def build_trie(words):
    root = {}
    for word in words:
        node = root
        for ch in word:
            node = node.setdefault(ch, {})
        node[END] = True
    return root

def contains(trie, word):
    node = trie
    for ch in word:
        if ch not in node:
            return False
        node = node[ch]
    return node.get(END, False)

def has_prefix(trie, prefix):
    node = trie
    for ch in prefix:
        if ch not in node:
            return False
        node = node[ch]
    return True

t = build_trie(['cat', 'car', 'card', 'care', 'dog'])
print(contains(t, 'car'))      # True
print(contains(t, 'card'))     # True
print(contains(t, 'ca'))       # False (prefix only, not a stored word)
print(contains(t, 'cards'))    # False (no word continues past 'card')
print(has_prefix(t, 'ca'))     # True
print(has_prefix(t, 'do'))     # True
print(has_prefix(t, 'fish'))   # False

The dict-of-dicts shape is the simplest trie that works: every node is a dict, keys are next characters, values are child dicts. A sentinel key ('__end__' here) marks 'a word ends at this node', which is what distinguishes a stored word from a mere prefix. setdefault is the one-liner for 'get or create the next node'. Insertion and lookup are both O(length) and the storage cost is one dict entry per character of input. This is the right starting trie for autocomplete prototypes, spell checkers, and the LeetCode 'Implement Trie' family.