4

I'm trying to figure out how, given multiple values, I can generate all combinations of the values when applies to a template / pattern. So if I have the following variables:

pattern = '{name} likes {animal}s'
options = {'name': ['Alex', 'Sarah', 'Bob'], 'animal': ['cat', 'dog']}

I'd like to have the code print out all the possible combinations based on the string pattern and the values in the dictionary (or any other structure, it doesn't matter)

'Alex likes cats'
'Alex likes dogs'
'Sarah likes cats'
'Sarah likes dogs'
'Bob likes cats'
'Bob likes dogs'

I can think of some ways do it, but it's messy, and I'm trying to find a way to do this without hardcoding, so in the future I could introduce a new key, like 'color' without having to change anything but pattern and options

I'm assuming I can use something similar to this code I found:

def combine(template, options):
    for opts in itertools.product(*options):
        yield template.format(*opts)

But I can't figure out how to get all the combinations and keep them in a format that string.format() will accept. I'm sure there's some simple solution I'm overlooking.

3
  • 1
    Check out itertools product Commented Oct 28, 2015 at 21:57
  • 1
    you could do a re.findall to look for all instances of \{([^}]\)}' then do an itertools.product` run of all the keys Commented Oct 28, 2015 at 21:57
  • Thanks both, I'll read more up on that to get a better understanding :) Commented Oct 28, 2015 at 21:59

1 Answer 1

4

So I found this out after stumbling upon another question, I'll leave it up in case this helps anyone else:

def combine(template, options)
    products = [dict(zip(options, values)) for values in itertools.product(*options.values())]
    return [template.format(**p) for p in products]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.