[SOLVED] 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!


Here is a working solution

import re

dictionary = {'apple': '', 'water': '', 'weber': '', 'tiger': '', 'elder': '', 'rover': '', 'waver': ''}
keys = list(dictionary.keys()) # not necessary but I think it's cleaner

output_list = [key for key in keys if re.search(r'^w..er$', key)] 

First ^ assert this is the beginning of your word (prevent word that would not start with w but still have this pattern inside), re.match does it by default, . correspond to any character and $ as for ^ assert you touch the end of the string (here, the word).

Answered By – Apo

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *