Dynamically brute-force all numerical combinations

Question:

As the title says I’m trying to get all possible numerical combinations for an unknown number of parameters. I don’t mind if you use pandas or numpy. See the code section to understand my problem easily. Any help would be appreciated.

# n can be any integer. 4 is just an example.
n = 4 
possibleValues = range(1, n+1)
# [1, 2, 3, 4]

# The number of elements in this list is unknown. It's only 2 elements just for example
parameters = ["foo", "boo"]

Expected results:
{'foo': 1, 'boo': 1},
{'foo': 1, 'boo': 2},
{'foo': 1, 'boo': 3},
{'foo': 1, 'boo': 4},

{'foo': 2, 'boo': 1},
{'foo': 2, 'boo': 2},
{'foo': 2, 'boo': 3},
{'foo': 2, 'boo': 4}

...

{'foo': 4, 'boo': 1},
{'foo': 4, 'boo': 2},
{'foo': 4, 'boo': 3},
{'foo': 4, 'boo': 4}
Asked By: Artur Nawrot

||

Answers:

itertools.product() will do this for you. You need to tell it how many to repeat, which in this case is the length of the dict keys. Then just zip them up and pass to dict():

from itertools import product

n = 4 
possibleValues = range(1, n+1)
parameters = ["foo", "boo"]

[dict(zip(parameters, pair)) for pair in product(possibleValues, repeat=len(parameters))]

Which gives you:

[{'foo': 1, 'boo': 1},
 {'foo': 1, 'boo': 2},
 {'foo': 1, 'boo': 3},
 {'foo': 1, 'boo': 4},
 {'foo': 2, 'boo': 1},
 {'foo': 2, 'boo': 2},
 {'foo': 2, 'boo': 3},
 {'foo': 2, 'boo': 4},
 {'foo': 3, 'boo': 1},
 {'foo': 3, 'boo': 2},
 {'foo': 3, 'boo': 3},
 {'foo': 3, 'boo': 4},
 {'foo': 4, 'boo': 1},
 {'foo': 4, 'boo': 2},
 {'foo': 4, 'boo': 3},
 {'foo': 4, 'boo': 4}]
Answered By: Mark
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.