Reputation: 29
I don't know if the title I gave does a good job of explaining what I need my program to do. I will have dictionaries of the form:
main_dictionary = {1: [ [a], [b], [c], ... ], 2: [ [a], [b], [c], ... ] , ... }
The dictionary can be arbitrarily long and have an arbitrary number of options for each key. I need the program to then make every permutation of this dictionary to test.
sub_dictionary = {1: [a], 2: [a], ... }
test_program(sub_dictionary)
sub_dictionary = {1: [a], 2: [b], ... }
test_program(sub_dictionary)
Upvotes: 1
Views: 72
Reputation: 164823
Here is one way using itertools.product
. The result is a list of "sub-dictionaries".
For simplicity, I have used a list of integers as values, but this can be replaced by values of your choice.
from itertools import product
d = {1: [3, 4, 5], 2: [6, 7, 8]}
values = list(zip(*sorted(d.items())))[1]
res = [dict(enumerate(x, 1)) for x in product(*values)]
If you need to test each dictionary individually, use a generator expression instead and iterate it:
for item in (dict(enumerate(x, 1)) for x in product(*values)):
...
If you have string keys:
res = [dict(zip(sorted(d), x)) for x in product(*values)]
Result:
[{1: 3, 2: 6},
{1: 3, 2: 7},
{1: 3, 2: 8},
{1: 4, 2: 6},
{1: 4, 2: 7},
{1: 4, 2: 8},
{1: 5, 2: 6},
{1: 5, 2: 7},
{1: 5, 2: 8}]
Upvotes: 1