Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing words in a string with multiple dictionary values?

I have a sentence template string and a dictionary of desired replacement words:

template = "Who was <Name>'s <Job> in <Month>?"
dictionary = {Name: [John,Peter,Paul],
              Job:  [Designer,Carpenter,Lawyer],
              Month:[October,July,March]
             }

I want to generate a list of sentences, one for each combination of replacements:

question_list=["Who was <John>'s <Lawyer> in <October>?",
               "Who was <Peter>'s <Lawyer> in <October>?",
               "Who was <John>'s <Designer> in <July>?",
               ... ]

The order of the list doesn't matter, and I don't need to remove the brackets '< >'.

At the moment I have:

def replace(template, dictionary):
    question_list = []
    for word in template:
        for key in dictionary:
            if word == key:
                new_string = template.replace(word, dictionary[key])
                question_list.append(new_string)
            return question_list

This returns question_list as an empty list.

I'm pretty sure my main problem is I don't know how/don't have a third for loop to access each item in the dictionary value lists, but I don't have enough experience to know how badly I'm screwing up. How do I fix this?

like image 437
re_ed1138 Avatar asked Oct 21 '25 03:10

re_ed1138


1 Answers

If this was 3.6 and you can change your string, to an f-string and product you don't need regex to deal with it:

dictionary = {'Name':['John','Peter','Paul'],'Job':['Designer','Carpenter','Lawyer'],'Month':['October','July','March']}

from itertools import product

l = [f"Who was {name}'s {job} in {month}?" for name, job, month in product(*dictionary.values())]

print(l)
like image 163
MooingRawr Avatar answered Oct 23 '25 21:10

MooingRawr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!