Open In App

Python – Find Keys with specific suffix in Dictionary

Last Updated : 22 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Keys with specific suffix in Dictionary
# Using dictionary comprehension + endswith()
 
# Initialize dictionary
test_dict = {'all': 4, 'geeks': 5, 'are': 8, 'freaks': 10}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize suffix
test_suf = 'ks'
 
# Using dictionary comprehension + endswith()
# Keys with specific suffix in Dictionary
res = {key: val for key, val in test_dict.items() if key.endswith(test_suf)}
 
# printing result
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




# Python3 code to demonstrate working of
# Keys with specific suffix in Dictionary
# Using map() + filter() + items() + endswith()
 
# Initialize dictionary
test_dict = {'all': 4, 'geeks': 5, 'are': 8, 'freaks': 10}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize suffix
test_suf = 'ks'
 
# Using map() + filter() + items() + endswith()
# Keys with specific suffix in Dictionary
res = dict(filter(lambda item: item[0].endswith(test_suf), test_dict.items()))
 
# printing result
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




# Python3 code to demonstrate working of
# Keys with specific suffix in Dictionary
 
# Initialize dictionary
test_dict = {'geeks': 5, 'are': 8, 'freaks': 10}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize suffix
test_suf = 'ks'
 
# Keys with specific suffix in Dictionary
d = dict()
for i in test_dict.keys():
    if(i.find(test_suf) == len(i)-len(test_suf)):
        d[i] = test_dict[i]
 
# printing result
print("Filtered dictionary keys are : " + str(d))


Output

The 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
 
# Initialize dictionary
test_dict = {'all': 4, 'geeks': 5, 'are': 8, 'freaks': 10}
 
# Initialize suffix
test_suf = 'ks'
 
# Use re.search() to check if keys match the pattern
res = {key: val for key, val in test_dict.items() if re.search(f"{test_suf}$", key)}
 
# printing result
print("Filtered dictionary keys are : " + str(res))
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

Filtered 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:

  1. Initialize a dictionary test_dict with key-value pairs.
  2. Initialize a string variable test_suf to store the suffix to match.
  3. Initialize an empty dictionary filtered_dict to store the filtered key-value pairs.
  4. Use a for loop to iterate over each key-value pair in the test_dict dictionary.
  5. 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.
  6. If the key ends with the suffix, add the key-value pair to the filtered_dict dictionary.
  7. Print the filtered dictionary.

Python3




# Initialize dictionary
test_dict = {'all': 4, 'geeks': 5, 'are': 8, 'freaks': 10}
 
# Initialize suffix
test_suf = 'ks'
 
# Initialize an empty dictionary to store the filtered keys and values
filtered_dict = {}
 
# Loop through each key-value pair in the dictionary
for key, val in test_dict.items():
    # Check if the key ends with the suffix
    if key[-len(test_suf):] == test_suf:
        # Add the key-value pair to the filtered dictionary
        filtered_dict[key] = val
 
# Print the filtered dictionary
print("Filtered dictionary keys are: " + str(filtered_dict))


Output

Filtered 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():

  1. Initialize the dictionary and the suffix.
  2. 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.
  3. Use reduce to accumulate the filtered keys and values.
  4. Print the filtered dictionary.
     

Python3




from functools import reduce
 
# Initialize dictionary
test_dict = {'geeks': 5, 'are': 8, 'freaks': 10}
 
# printing original dictionary
print("The original dictionary : " + str(test_dict))
 
# Initialize suffix
test_suf = 'ks'
 
# Keys with specific suffix in the
# Dictionary using reduce
d = reduce(lambda acc, key: {**acc, key: test_dict[key]}, filter(
    lambda key: key.endswith(test_suf), test_dict.keys()), {})
 
# Print the result
print("Filtered dictionary keys are : " + str(d))


Output

The 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads