Python - Prefix key match in dictionary


Introduction

Python could be a flexible programming dialect eminent for its effortlessness and coherence. One of its effective highlights is the capacity to perform prefix key coordinating in word references. This usefulness empowers effective looking for keys that start with a particular prefix. In this article, we'll investigate three approaches to actualize prefix key coordination in Python, at the side their comparing calculations, step-by-step enlightening, Python sentence structure, and code illustrations. By leveraging these procedures, able to altogether improve our capacity to control and extricate information successfully. Let's plunge into the world of prefix key coordinating!

Approach 1: Linear Search

Algorithm

The straight look approach may be a direct strategy to perform prefix key coordinating in a word reference. It includes repeating through all the keys and checking if each key begins with the required prefix. Here's the algorithmic portrayal and step-by-step directions for this approach −

  • Step 1 - Define a function prefix_match_linear() and initialize an empty list to store coordinating keys

  • Step 2 - Repeat through each key within the lexicon

  • Step 3 - Check if the key begins with the specified prefix.

  • Step 4 - On the off chance that the prefix coordinate is found, add the key to the list.

  • Step 5 - Rehash steps 3-4 for all keys

  • Step 6 - Return the list of coordinating keys. 

Example

def prefix_match_linear(dictionary, prefix):
    matches = []
    for key in dictionary.keys():
        if key.startswith(prefix):
            matches.append(key)
    return matches


fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

prefix = 'app'
matches = prefix_match_linear(fruit_dict, prefix)
print(matches)

Output

['apple']

Approach 2:  Trie Data Structure

The Trie information structure may be a tree-like structure that exceeds expectations at efficient prefix matching. Let's investigate how to utilize the Trie information structure to perform prefix key coordinating −

Algorithm

  • Step 1 - Define a dictionary that contains multiple elements.

  • Step 2 - Create two classes separately named TrieNode and Trie. Create the non-parameterized constructor in the TrieNode and set their attribute with certain values.

  • Step 3 - Similarly, define the constructor in Trie class and create the user-defined function insert inside the Trie class, and use for loop to iterate through each key within the word reference

  • Step 4 - Embed each key into the Trie

  • Step 5 - Hunt for the specified prefix within the Trie.

  • Step 6 - Recover all the keys that coordinate the prefix

Example

fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end_of_word = False


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

    def insert(self, word):
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end_of_word = True

    def get_matches(self, prefix):
        node = self.root
        matches = []
        for char in prefix:
            if char not in node.children:
                return matches
            node = node.children[char]
        self._collect_matches(node, prefix, matches)
        return matches

    def _collect_matches(self, node, prefix, matches):
        if node.is_end_of_word:
            matches.append(prefix)
        for char, child in node.children.items():
            self._collect_matches(child, prefix + char, matches)


def prefix_match_trie(dictionary, prefix):
    trie = Trie()
    for key in dictionary.keys():
        trie.insert(key)
    return trie.get_matches(prefix)


prefix = 'ban'
matches = prefix_match_trie(fruit_dict, prefix)
print(matches)

Output

['banana']

Approach 3:  Using Python's Built-in Filter Function

Python gives a built-in filter() function that permits us to form an effective one-liner to perform prefix key coordinating. By applying this work to the lexicon keys and lambda work, we will accomplish brief and lucid code. Here's how it works −

Algorithm

  • Step 1 - Create a dictionary named fruit_dict.

  • Step 2 - Define a function prefix_match_filter() that contains two arguments in the function definition and then make a lambda work that checks on the off chance that each key begins with the required prefix.

  • Step 3 - Apply the filter() function to the word reference keys, utilizing the lambda work as the channel condition.

  • Step 4 - Collect the resultant keys in a list.

  • Step 5 - Invoke the function and pass its value to the variable named matches.

  • Step 6 - Finally, print the value of the matches.

Example

fruit_dict = {
    'apple': 1,
    'apricot': 2,
    'banana': 3,
    'orange': 4,
    'pineapple': 5
}

def prefix_match_filter(dictionary, prefix):
    matches = list(filter(lambda key: key.startswith(prefix), dictionary.keys()))
    return matches

prefix = 'or'
matches = prefix_match_filter(fruit_dict, prefix)
print(matches)

Output

['orange']

Conclusion

In this article, we investigated three approaches to execute prefix key coordinating in Python lexicons. We secured the direct look approach, which is basic but less productive for bigger datasets. At that point, we dug into the Trie information structure, which exceeds expectations at prefix coordinating with made strides in effectiveness. Each approach has its possess qualities and can be chosen based on the prerequisites of the assignment at hand. By acing prefix key coordinating procedures in Python, engineers can productively recover information from lexicons and streamline their information control assignments.

Updated on: 01-Sep-2023

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements