2

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' : 2 },
{ '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.

user
  • 7,123
  • 7
  • 48
  • 90

1 Answers1

9
[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)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358