0

Having the following dictionary:

d = {
  'a': [1, 2, 3],
  'b': [True, False]
}

How can I generate a list of dictionaries representing all combinations of the values for each key? The output should be like this:

combinations = [
  {'a': 1, 'b': True},
  {'a': 2, 'b': True},
  {'a': 3, 'b': True},
  {'a': 1, 'b': False},
  {'a': 2, 'b': False},
  {'a': 3, 'b': False}
]

This should work with an arbitrary number of keys and an arbitrary length of values in the dictionary. We can assume that the values are always a list.

Peque
  • 13,638
  • 11
  • 69
  • 105

1 Answers1

4

This can be solved using itertools:

[dict(zip(d, values)) for values in itertools.product(*d.values())]
Peque
  • 13,638
  • 11
  • 69
  • 105
  • If you're going to ask and self-answer (which is fine!) you should make sure to check for dups. This question is a dup of [this](http://stackoverflow.com/questions/26724860/get-list-of-all-possible-dict-configs-in-python) and [this](http://stackoverflow.com/questions/15211568/combine-python-dictionary-permutations-into-list-of-dictionaries) and probably others too. – DSM Oct 15 '15 at 11:55
  • @DSM: you are right. I always search for duplicates (because before having an answer, I had the question, so I was also interested in finding a solution), but didn't find anything. I also always check the "possible duplicates" list when asking a question, but no real duplicates were displayed in there. I guess sometimes it is not so easy to find actual duplicates (it seems YusufX couldn't find the duplicate either before asking the same question). Anyway, thanks for pointing that out. – Peque Oct 15 '15 at 11:59
  • @DSM: marked as duplicate. ;-) – Peque Oct 18 '15 at 18:46