Given a dictionary mapping variables to possible outcomes:
{ 'lblA' : [False, True], 'lblB' : [False, True], 'lblC' : [0,1,2] }
I want to enumerate all possible dictionary outcomes:
[ { 'lblA' : False , 'lblB' : False, 'lblC' : 0 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 0 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 0 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 0 },
{ 'lblA' : False , 'lblB' : False, 'lblC' : 1 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 1 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 1 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 1 },
{ 'lblA' : False , 'lblB' : False, 'lblC' : 开发者_如何学C2 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 2 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 2 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 2 } ]
I know that this could be done recursively, but I'd really like to do it with itertools
for speed.
Does anyone know the best way to do this?
Thanks a lot for your help!
Edit
I want to do this for an arbitrary dictionary.
[dict(zip(('lblA', 'lblB', 'lblC'), term)) for term in
itertools.product((False, True) , (False, True), (0, 1, 2))]
EDIT:
Picky, picky...
src = {'lblA': (False, True), 'lblB': (False, True), 'lblC': (0, 1, 2)}
labels, terms = zip(*src.items())
print [dict(zip(labels, term)) for term in itertools.product(*terms)]
精彩评论