2

I have a dictionary of lists, where each list represents all possible values for a variable (key):

# dictionary of lists
values = {1: [4, 7, 8], 
          2: [1, 3], 
          3: [7, 5, 6], 
          4: [2]}

I want to create tuples containing all possible permutations of these values (Cartesian product) so that I can determine which value combinations are correct.

# example
perms = [(4, 1, 7, 2), (4, 1, 5, 2), (4, 1, 6, 2), (4, 3, 7, 2), ... , (8, 3, 6, 2)]

Is there an easy way to go about this? I asked another problem and it was solved with itertools permutations. However I am confused as to how I would choose one number from multiple lists for the permutation.

1 Answer 1

3

This one needs a product.

>>> from itertools import product
>>> list(product(*values.values()))
[(4, 1, 7, 2),
 (4, 1, 5, 2),
 (4, 1, 6, 2),
 (4, 3, 7, 2),
 (4, 3, 5, 2),
 ...
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.