遍历 Python 字典中所有可能的参数组合。在每次迭代中将它们作为 kwargs 传递给函数

iterate over all possible combinations of params inside a Python dictionary. Pass them as kwargs into a function on each iteration

我有一个 Python 字典,其参数的动态长度如下:

'dynamic_params' : {
    'param_1' : [*range(1,3)],
    'param_2' : [*range(1,9)],
    ...
    'param_X' : [*range(1,6)],
},

我需要:

a) 遍历所有可能的组合。喜欢:

('param_1', 1), ('param_2', 1), ..., ('param_X', 1), 
('param_1', 1), ('param_2', 1), ..., ('param_X', 2),
... 
('param_1', 2), ('param_2', 8), ..., ('param_X', 5), 

我使用了‘itertools.product’,对于固定数量的参数没有问题。但我无法让它在这种情况下工作。

b) 在每次迭代中,将每个参数组合作为 kwargs 传递给函数。喜欢:

my_function(
    other_non_related_params,
    param_1 = 1,
    param_2 = 1,
    ...
    param_X = 1,
)
my_function(
    other_non_related_params,
    param_1 = 1,
    param_2 = 1,
    ...
    param_X = 2,
)
...
my_function(
    other_non_related_params,
    param_1 = 2,
    param_2 = 8,
    ...
    param_X = 5,
)

你建议如何解决这个问题?

谢谢!

您可以使用参数解构来取许多参数的笛卡尔积:

from itertools import product

# boilerplate function to print kwargs
def print_kwargs(**kwargs):
    print(kwargs)

dynamic_params = {
    "param_1": [1, 2],
    "param_2": [1, 2],
    "param_3": [1, 2, 3]
}

param_names = list(dynamic_params.keys())
# zip with parameter names in order to get original property
param_values = (zip(param_names, x) for x in product(*dynamic_params.values()))

for paramset in param_values:
    # use the dict from iterator of tuples constructor
    kwargs = dict(paramset)
    print_kwargs(**kwargs)

输出:

{'param_1': 1, 'param_2': 1, 'param_3': 1}
{'param_1': 1, 'param_2': 1, 'param_3': 2}
{'param_1': 1, 'param_2': 1, 'param_3': 3}
{'param_1': 1, 'param_2': 2, 'param_3': 1}
{'param_1': 1, 'param_2': 2, 'param_3': 2}
{'param_1': 1, 'param_2': 2, 'param_3': 3}
{'param_1': 2, 'param_2': 1, 'param_3': 1}
{'param_1': 2, 'param_2': 1, 'param_3': 2}
{'param_1': 2, 'param_2': 1, 'param_3': 3}
{'param_1': 2, 'param_2': 2, 'param_3': 1}
{'param_1': 2, 'param_2': 2, 'param_3': 2}
{'param_1': 2, 'param_2': 2, 'param_3': 3}