3

I have a dictionary where each value is a list of lists.

Something like:

sites = {'e1': [[0, 1, 3], [0, 2, 3]], 'e2': [[0, 1, 4], [0, 3, 4]]}

I want to loop through all possible combinations (i.e. pairs in my example) of lists (i.e. one list of e1 + one list of e2, etc.).

Better with the example:

I want to loop through all these combinations:

[0, 1, 3]; [0, 1, 4]
[0, 1, 3]; [0, 3, 4]
[0, 2, 3]; [0, 1, 4]
[0, 2, 3]; [0, 3, 4]

This example dictionary has two keys but in practice I do not know how many keys I'll have in my dictionary. It could be more than two.

Can you help?

francoiskroll
  • 1,026
  • 3
  • 13
  • 24

1 Answers1

5

You are looking for cartesian product between the list values of the dict. For achieving the desired result, you may use itertools.product as:

>>> from itertools import product
>>> sites = {'e1': [[0, 1, 3], [0, 2, 3]], 'e2': [[0, 1, 4], [0, 3, 4]]}

>>> list(product(*sites.values()))
[([0, 1, 3], [0, 1, 4]), 
 ([0, 1, 3], [0, 3, 4]), 
 ([0, 2, 3], [0, 1, 4]), 
 ([0, 2, 3], [0, 3, 4])]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126