Seth Johnson Seth Johnson - 24 days ago 6
Python Question

Cartesian product of a dictionary of lists

I'm trying to write some code to test out the Cartesian product of a bunch of input parameters.

I've looked at

itertools
, but its
product
function is not exactly what I want. Is there a simple obvious way to take a dictionary with an arbitrary number of keys and an arbitrary number of elements in each value, and then yield a dictionary with the next permutation?

Input:

options = {"number": [1,2,3], "color": ["orange","blue"] }
print list( my_product(options) )


Example output:

[ {"number": 1, "color": "orange"},
{"number": 1, "color": "blue"},
{"number": 2, "color": "orange"},
{"number": 2, "color": "blue"},
{"number": 3, "color": "orange"},
{"number": 3, "color": "blue"}
]

Answer

Ok, thanks to @dfan for telling me I was looking in the wrong place. I've got it now:

def my_product(dicts):
    return (dict(izip(dicts, x)) for x in product(*dicts.itervalues()))