Python | Prefix key match in dictionary
Last Updated :
08 May, 2023
Sometimes, while working with dictionaries, we can have a problem in which we need to find the dictionary items that have some constraints on keys. One such constraint can be a prefix match on keys. Let’s discuss certain ways in which this task can be performed.
Method #1: Using dictionary comprehension + startswith()
The combination of above two methods can be used to perform this particular task. In this, dictionary comprehension does the basic task of dictionary construction and startswith() performs the utility task of checking keys starting with specific prefix.
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
res = {key: val for key, val in test_dict.items()
if key.startswith(test_pref)}
print ( "Filtered dictionary keys are : " + str (res))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary Space: O(m), where m is the number of keys in the filtered dictionary
Method #2 : Using map() + filter() + items() + startswith() This particular task can also be performed using the combination of above functions. The map function ties the filter logic of startswith() to each dictionary’s items extracted by items()
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
res = dict ( filter ( lambda item: item[ 0 ].startswith(test_pref),
test_dict.items()))
print ( "Filtered dictionary keys are : " + str (res))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time complexity: O(n), where n is the number of items in the dictionary. This is because we are iterating over the items in the dictionary and applying the startswith function to each key, which takes O(m), where m is the length of the key.
Auxiliary Space: O(k), where k is the number of items that match the prefix, because the filtered dictionary contains only the items that match the prefix.
Method #3: Using find() method
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
res = {key:val for key, val in test_dict.items()
if key.find(test_pref) = = 0 }
print ( "Filtered dictionary keys are : " + str (res))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time complexity: O(n) where n is the number of items in the dictionary.
Auxiliary space: O(m) where m is the number of items in the filtered dictionary.
Method #4 : use re.match()
Python3
import re
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
res = {key: val for key, val in test_dict.items()
if re.match(test_pref, key)}
print ( "Filtered dictionary keys are : " + str (res))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using slicing
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
res = dict ()
for i in list (test_dict.keys()):
if (i[: len (test_pref)] = = test_pref):
res[i] = test_dict[i]
print ( "Filtered dictionary keys are : " + str (res))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 6: Using a list comprehension
Step-by-step approach
- Initialize the original dictionary.
- Print the original dictionary.
- Initialize the prefix string.
- Use a list comprehension to filter out the keys that start with the given prefix.
- Create a new dictionary using the filtered keys and their corresponding values from the original dictionary.
- Print the filtered dictionary.
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
filtered_keys = [key for key in test_dict.keys() if key.startswith(test_pref)]
filtered_dict = {key: test_dict[key] for key in filtered_keys}
print ( "Filtered dictionary keys are : " + str (filtered_dict))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
The time complexity of this method is O(n), where n is the number of keys in the dictionary.
The space complexity is O(k), where k is the number of keys that start with the given prefix.
Method #7: Using a for loop
Step-by-step explanation:
- Initialize the dictionary test_dict.
- Print the original dictionary using print().
- Initialize the prefix test_pref.
- Initialize an empty dictionary filtered_dict.
- Use a for loop to iterate through each key in test_dict.
- Use the startswith() method to check if the key starts with test_pref.
- If the key starts with test_pref, add the key-value pair to filtered_dict.
- Print the filtered dictionary using print().
Python3
test_dict = { 'tough' : 1 , 'to' : 2 , 'do' : 3 , 'todays' : 4 , 'work' : 5 }
print ( "The original dictionary : " + str (test_dict))
test_pref = 'to'
filtered_dict = {}
for key in test_dict.keys():
if key.startswith(test_pref):
filtered_dict[key] = test_dict[key]
print ( "Filtered dictionary keys are : " + str (filtered_dict))
|
Output
The original dictionary : {'tough': 1, 'to': 2, 'do': 3, 'todays': 4, 'work': 5}
Filtered dictionary keys are : {'tough': 1, 'to': 2, 'todays': 4}
Time complexity: O(n), where n is the number of keys in the dictionary.
Auxiliary space: O(k), where k is the number of keys that start with
Similar Reads
Add Prefix to Each Key Name in Dictionary - Python
Adding a prefix to each key in a dictionary is a common task when manipulating or organizing data. For example, we might want to indicate the source of the keys or make them more descriptive. Let's explore multiple methods to achieve this in Python. Using Dictionary ComprehensionWe can use dictionar
2 min read
Python | Substring Key match in dictionary
Sometimes, while working with dictionaries, we might have a use case in which we are not known the exact keys we require but just a specific part of keys that we require to fetch. This kind of problem can arise in many applications. Let's discuss certain ways in which this problem can be solved. Met
9 min read
Get Next Key in Dictionary - Python
We are given a dictionary and need to find the next key after a given key, this can be useful when iterating over dictionaries or accessing elements in a specific order. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} if the current key is "b" then the next key should b
2 min read
Python - Initialize dictionary keys with Matrix
Sometimes, while working with Python Data, we can have a problem in which we need to construct an empty mesh of dictionaries for further population of data. This problem can have applications in many domains which include data manipulation. Let's discuss certain ways in which this task can be perfor
4 min read
How to Print Dictionary Keys in Python
We are given a dictionary and our task is to print its keys, this can be helpful when we want to access or display only the key part of each key-value pair. For example, if we have a dictionary like this: {'gfg': 1, 'is': 2, 'best': 3} then the output will be ['gfg', 'is', 'best']. Below, are the me
2 min read
Python - Key Columns Dictionary from Matrix
Given a Matrix and list of keys, map each column's values with a custom list key. Input : test_list1 = [[4, 6], [8, 6]], test_list2 = ["Gfg", "Best"] Output : {'Gfg': [4, 8], 'Best': [6, 6]} Explanation : Column wise, Key values assignment.Input : test_list1 = [[4], [6]], test_list2 = ["Gfg"] Output
6 min read
Key Index in Dictionary - Python
We are given a dictionary and a specific key, our task is to find the index of this key when the dictionaryâs keys are considered in order. For example, in {'a': 10, 'b': 20, 'c': 30}, the index of 'b' is 1. Using dictionary comprehension and get()This method builds a dictionary using dictionary com
2 min read
Dictionary keys as a list in Python
In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
2 min read
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Python - Extracting Kth Key in Dictionary
Many times, while working with Python, we can have a situation in which we require to get the Kth key of dictionary. There can be many specific uses of it, either for checking the indexing and many more of these kind. This is useful for Python version 3.8 +, where key ordering are similar as inserti
4 min read