Skip to content
Advertisement

All unique combinations of a set of sets of values

If I have an arbitrary amount of elements, each with a specified set of values, what can I do to get all possible combinations with a value from each element’s set?

For example, let’s say I have:

elems = {"A": (0, 1), "B": (-1, -5)}

What can I do to get the following?

({"A": 0, "B": -1}, {"A": 0, "B": -5}, {"A": 1, "B": -1}, {"A": 1, "B": -5})

Input/output don’t need to use dicts, but I figured that’s the easiest way to represent it. Assume dict order matters.

I would like to know a way that:

  1. Does not assume there are just 2 elements like in the example.
  2. Does not assume the sets for all elements have an equal length.

It is somewhat like listing all inputs for a truth table.

Advertisement

Answer

You can use a nested list/dictionary comprehension, using itertools.product to generate all combinations of the values, and then ziping each result tuple from that to the keys to generate the key/value pairs to make up each dictionary result. Here’s an example using a slightly more complicated version of your data:

import itertools

elems = {"A": (0, 1), "B": (-1, -5), "C": (1, 2, 3) }

keys = elems.keys()
res = [dict(zip(keys, p)) for p in itertools.product(*elems.values())]

Output:

[
 {'A': 0, 'B': -1, 'C': 1},
 {'A': 0, 'B': -1, 'C': 2},
 {'A': 0, 'B': -1, 'C': 3},
 {'A': 0, 'B': -5, 'C': 1},
 {'A': 0, 'B': -5, 'C': 2},
 {'A': 0, 'B': -5, 'C': 3},
 {'A': 1, 'B': -1, 'C': 1},
 {'A': 1, 'B': -1, 'C': 2},
 {'A': 1, 'B': -1, 'C': 3},
 {'A': 1, 'B': -5, 'C': 1},
 {'A': 1, 'B': -5, 'C': 2},
 {'A': 1, 'B': -5, 'C': 3}
]
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement