How can I make a list of dictionaries according to the Cartesian product of values in a source dictionary ("explode" the dictionary)?

cartesian-product, dictionary, python

Solution

I think you want the Cartesian product, not a permutation, in which case `itertools.product` can help:

>>> from itertools import product
>>> d = {'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large']}
>>> [dict(zip(d, v)) for v in product(*d.values())]
[{'Color': 'Red', 'Size': 'Small'}, {'Color': 'Red', 'Size': 'Medium'}, {'Color': 'Red', 'Size': 'Large'}, {'Color': 'Yellow', 'Size': 'Small'}, {'Color': 'Yellow', 'Size': 'Medium'}, {'Color': 'Yellow', 'Size': 'Large'}]

Problem

Given a dictionary that looks like this: ``` { 'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large'] } ``` How can I create a list of dictionaries that combines the various values of the first dictionary's keys? What I want is: ``` [ {'Color': 'Red', 'Size': 'Small'}, {'Color': 'Red', 'Size': 'Medium'}, {'Color': 'Red', 'Size': 'Large'}, {'Color': 'Yellow', 'Size': 'Small'}, {'Color': 'Yellow', 'Size': 'Medium'}, {'Color': 'Yellow', 'Size': 'Large'} ] ```

Original source

Related problems