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 suffix match on keys. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehension + endswith()
The combination of the above two methods can be used to perform this particular task. In this, dictionary comprehension does the basic task of dictionary construction and endswith() performs the utility task of checking keys starting with specific suffix.
Python3
test_dict = { 'all' : 4 , 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
print ( "The original dictionary : " + str (test_dict))
test_suf = 'ks'
res = {key: val for key, val in test_dict.items() if key.endswith(test_suf)}
print ( "Filtered dictionary keys are : " + str (res))
|
Output : The original dictionary : {'geeks': 5, 'freaks': 10, 'are': 8, 'all': 4}
Filtered dictionary keys are : {'geeks': 5, 'freaks': 10}
Method #2: Using map() + filter() + items() + endswith()
This particular task can also be performed using a combination of the above functions. The map function ties the filter logic of endswith() to each dictionary’s items extracted by items().
Python3
test_dict = { 'all' : 4 , 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
print ( "The original dictionary : " + str (test_dict))
test_suf = 'ks'
res = dict ( filter ( lambda item: item[ 0 ].endswith(test_suf), test_dict.items()))
print ( "Filtered dictionary keys are : " + str (res))
|
Output : The original dictionary : {'geeks': 5, 'freaks': 10, 'are': 8, 'all': 4}
Filtered dictionary keys are : {'geeks': 5, 'freaks': 10}
Method #3 : Using find() method
Python3
test_dict = { 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
print ( "The original dictionary : " + str (test_dict))
test_suf = 'ks'
d = dict ()
for i in test_dict.keys():
if (i.find(test_suf) = = len (i) - len (test_suf)):
d[i] = test_dict[i]
print ( "Filtered dictionary keys are : " + str (d))
|
OutputThe original dictionary : {'geeks': 5, 'are': 8, 'freaks': 10}
Filtered dictionary keys are : {'geeks': 5, 'freaks': 10}
The time complexity of this approach is O(n*k), where n is the number of keys in the input dictionary and k is the length of the suffix.
The auxiliary space complexity of this approach is O(m), where m is the number of keys in the filtered dictionary.
Method #4: Using re
One approach to finding keys with a specific suffix in a dictionary is to use the re (regular expression) module in Python.
You can use the re.search() function to check if a key matches a specific regular expression pattern (in this case, a pattern that matches keys that end with a specific suffix).
Example:
Python3
import re
test_dict = { 'all' : 4 , 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
test_suf = 'ks'
res = {key: val for key, val in test_dict.items() if re.search(f "{test_suf}$" , key)}
print ( "Filtered dictionary keys are : " + str (res))
|
OutputFiltered dictionary keys are : {'geeks': 5, 'freaks': 10}
In this example, f”{test_suf}$” is the regular expression pattern that matches keys that end with the value of test_suf. The $ at the end of the pattern indicates that the pattern should match the end of the string.
The time complexity for this approach is O(n) where n is the number of keys in the dictionary. The auxiliary space is O(m) where m is the number of keys that match the regular expression pattern.
Method #5: Using a for loop and string slicing
Approach:
- Initialize a dictionary test_dict with key-value pairs.
- Initialize a string variable test_suf to store the suffix to match.
- Initialize an empty dictionary filtered_dict to store the filtered key-value pairs.
- Use a for loop to iterate over each key-value pair in the test_dict dictionary.
- For each key-value pair, check if the key ends with the suffix by using string slicing to extract the last len(test_suf) characters of the key and comparing it to the suffix.
- If the key ends with the suffix, add the key-value pair to the filtered_dict dictionary.
- Print the filtered dictionary.
Python3
test_dict = { 'all' : 4 , 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
test_suf = 'ks'
filtered_dict = {}
for key, val in test_dict.items():
if key[ - len (test_suf):] = = test_suf:
filtered_dict[key] = val
print ( "Filtered dictionary keys are: " + str (filtered_dict))
|
OutputFiltered dictionary keys are: {'geeks': 5, 'freaks': 10}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(k), where k is the number of key-value pairs that match the suffix. In the worst case, where all keys match the suffix, the filtered dictionary will be the same size as the original dictionary.
Method #6: Using reduce():
- Initialize the dictionary and the suffix.
- Define a lambda function that takes two parameters as input, acc, and key, and returns a dictionary consisting of acc and key from the test_dict if the key ends with the test_suf.
- Use reduce to accumulate the filtered keys and values.
- Print the filtered dictionary.
Python3
from functools import reduce
test_dict = { 'geeks' : 5 , 'are' : 8 , 'freaks' : 10 }
print ( "The original dictionary : " + str (test_dict))
test_suf = 'ks'
d = reduce ( lambda acc, key: { * * acc, key: test_dict[key]}, filter (
lambda key: key.endswith(test_suf), test_dict.keys()), {})
print ( "Filtered dictionary keys are : " + str (d))
|
OutputThe original dictionary : {'geeks': 5, 'are': 8, 'freaks': 10}
Filtered dictionary keys are : {'geeks': 5, 'freaks': 10}
Time Complexity: The time complexity of this code is O(n), where n is the number of keys in the dictionary.
Space Complexity: The space complexity of this code is O(n), where n is the number of keys in the dictionary. The space required to store the filtered dictionary is proportional to the number of keys that satisfy the filter condition.