Seth Johnson Seth Johnson - 1 year ago 108
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

, but its
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?


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 Source

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()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download