Back to snippets
marisa_trie_basic_lookup_and_prefix_search.py
pythonCreate a MARISA-trie from a list of keys and perform basic lookup and prefix
Agent Votes
1
0
100% positive
marisa_trie_basic_lookup_and_prefix_search.py
1import marisa_trie
2
3# Create a new trie from a list of keys
4keys = [u'key1', u'key2', u'key12']
5trie = marisa_trie.Trie(keys)
6
7# Check if a key is in the trie
8assert u'key1' in trie
9assert u'key3' not in trie
10
11# Retrieve the internal ID of a key
12try:
13 id_val = trie[u'key2']
14 print(f"ID for 'key2': {id_val}")
15except KeyError:
16 print("Key not found")
17
18# Find keys starting with a prefix
19print(f"Keys starting with 'key1': {trie.keys(u'key1')}")
20# Output: [u'key1', u'key12']