I want evaluate a function for all possible combinations of arguments (of potentiall different amount) given in a dictionary at most using the numpy package.
args1 = {'a' : [1, 2, 3], 'b' : [6, 7]}
args2 = {'a' : [1, 2, 3], 'b' : [6, 7], 'c' : [5, 4}
def fun(a, b, c = 1):
return a b c
# What I want to automate:
fun(args1['a'][0], args1['b'][0])
fun(args1['a'][1], args1['b'][0])
.
.
.
fun(args2['a'][2], args2['b'][1], args2['c'][0])
fun(args2['a'][2], args2['b'][1], args2['c'][1])
Is there an elegant way to do this? I was thinking about convert 'args' to a list of all the combinations of dictionaries (can't wrap my head around how one would do this... Maybe with dictionary comprehension?), and then use map(). Or maybe np.frompyfunc could work, but I can't find a way to convert the dictionary...
CodePudding user response:
One approach is to use itertools.product to generate the combinations
from itertools import product
args1 = {'a': [1, 2, 3], 'b': [6, 7]}
args2 = {'a': [1, 2, 3], 'b': [6, 7], 'c': [5, 4]}
def fun(a, b, c=1):
return a b c
for pair in product(*args1.values()):
res = fun(**dict(zip(args1, pair)))
print(res)
Output
8
9
9
10
10
11
Or as an alternative, as long as the keys of the dictionary are in the same order (of insertion) as the parameters:
for pair in product(*args1.values()):
res = fun(*pair)
print(res)