'Python Function that Match a Given Template
Say I have a template and I have a dictionary containing words. I want to create a function that returns a list of words that match the given template. To illustrate this:
template = 'W**ER'
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
Desired output:
output_list = ['water', 'weber', 'waver']
I'm not entirely sure how to create the function and I would totally appreciate any help. Thanks!
Solution 1:[1]
You can use regular expression to find a matched keys with the templete.
My code find all the matched keys, and it is case-insensitive code, as follows:
import re
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
output = []
for key in dictionary.keys():
matched = re.match("[Ww]+..[Ee]+[Rr]+$", key) # case-insensitive, 5 letters
if matched:
output.append(key)
print(output)
#['water', 'weber', 'waver']
For more information about regular expressions with examples, you can see: https://docs.python.org/3/library/re.html
Solution 2:[2]
As all the answers contain '.' as any symbol, although it may be better to use any letter instead. Also note having start of string and end of string. That means that waterdasdadad won't proceed
Here is my code
import re
template = r'^w\w\wer$' # means start of string, w, any alphabet char twice, e, r, end of string
regex = re.compile(template)
dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
output_list = list()
for key in dictionary:
if regex.fullmatch(key): # use key.lower() for case insensitivity
output_list.append(key)
print(output_list)
Solution 3:[3]
Try to use regex:
import re
ptrn = re.compile("w..er")
list(filter(lambda key: re.match(ptrn, key), dictionary))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | sudden_appearance |
| Solution 3 |
