I have a arbitrary number of variables with arbitrary number of valid values each variable can take. For eg. a - (a1,a2,a3), b - (b1,b2), c - (c1,c2,c3,c4,c5). Now I wanted the a list of dictionaries as below
[
{a:a1,b:b1,c:c1},
{a:a1,b:b1,c:c2},
{a:a1,b:b1,c:c3},
.
.
.
{a:a3,b:b2,c:c3}
]
Total 3*2*5 = 30 combinations will come for the above scenario. How to create them in python.
I could have three for
loops for each variable as below
result_list = list()
for a_val in [a1,a2,a3]:
for b_val in [b1,b2]:
for c_val in [c1,c2,c3,c4,c5]:
result_list.append({a:a_val,b:b_val,c:c_val})
But the number of variables also vary. Instead of 3 variables, I wanted to apply on 5 variables as well (a,b,c,d,e) and so on. How to have a common code to achieve this in python
The simplest way to do this is itertools.product()
.
It allows you to create what you want in a simple one-liner:
import itertools
a = [1,2,3]
b = [4,5]
c = [-1]
# result contains all possible combinations.
combinations = list(itertools.product(a,b,c))
Note that the resulting combinations
variable itself is a list
(could be cast to a set
), and the different elements are tuples
, not dicts
.
I currently don't see the exact reasoning why you would have to name your elements in a dict-like fashion, as long as you know in which order the elements are stored there (which is predictable in itertools.product
.