How to generate all combination from values in dict of lists in Python
import itertools as itmy_dict={'A':['D','E'],'B':['F','G','H'],'C':['I','J']}allNames = sorted(my_dict)combinations = it.product(*(my_dict[Name] for Name in allNames))print(list(combinations))
Which prints:
[('D', 'F', 'I'), ('D', 'F', 'J'), ('D', 'G', 'I'), ('D', 'G', 'J'), ('D', 'H', 'I'), ('D', 'H', 'J'), ('E', 'F', 'I'), ('E', 'F', 'J'), ('E', 'G', 'I'), ('E', 'G', 'J'), ('E', 'H', 'I'), ('E', 'H', 'J')]
If you want to keep the key:value
in the permutations you can use:
import itertoolskeys, values = zip(*my_dict.items())permutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)]
this will provide you a list of dicts with the permutations:
print(permutations_dicts)[{'A':'D', 'B':'F', 'C':'I'}, {'A':'D', 'B':'F', 'C':'J'}, ... ]
disclaimer
not exactly what the OP was asking, but google send me here looking for that.
How about using ParameterGrid from scikit-learn? It creates a generator over which you can iterate in a normal for loop. In each iteration, you will have a dictionary containing the current parameter combination.
from sklearn.model_selection import ParameterGridparams = {'A':['D','E'],'B':['F','G','H'],'C':['I','J']}param_grid = ParameterGrid(params)for dict_ in param_grid: # Do something with the current parameter combination in ``dict_`` print(dict_["A"]) print(dict_["B"]) print(dict_["C"])