Prefix matching in Python using pytrie module

PythonServer Side ProgrammingProgramming

In this article, we are going to learn about the pytrie module to prefix matching strings from a list of strings. Let's see an example to understand it clearly.

List: ['tutorialspoint', 'tutorials', 'tutorialspython', 'python']
Prefix: 'tutorials'

['tutorialspoint', 'tutorials', 'tutorialspython']

We can achieve it in different ways. In this tutorial, we are going to achieve it using the pytrie module.

From pytrie module, we will use the pytrie.StringTrie data structure. We can perform create, insert, search, and delete operations.

First, install the pytrie module with the following command.

pip install pytrie

Let's see steps to achieve the desired output.

  • Import the pytrie module.
  • Initialize the list, prefix.
  • Create a trie data structure using pytrie.StringTrie().
  • Iterate over the list and insert into the trie structure.
  • And print the values matching given prefix.


# importing the module
import pytrie

# initializing the list and prefix
strings = ['tutorialspoint', 'tutorials', 'tutorialspython', 'python', 'learnpython']
prefix = 'tutorials'

# creating an trie data structure
trie = pytrie.StringTrie()

# iterating over the list and adding it to trie
for item in strings:
   trie[item] = item

# printing the matched strings

If you execute the above code, then you will get the following result.


['tutorials', 'tutorialspoint', 'tutorialspython']


If you have any doubts in the tutorial, mention them in the comment section.

Published on 13-Nov-2020 17:33:21