I need to generate a list of dicts that show all possible permutations of two values. (I’m testing UI components so I need to see how they render in all possible circumstances, however unlikely.) I can do it with a list comprehension:
values = [True, False]
variants = ({
'Field X': x,
'Field Y': y,
'Field Z': z,
} for x in values for y in values for z in values)
to produce:
>>> list(variants)
[{'Field X': True, 'Field Y': True, 'Field Z': True}, {'Field X': True, 'Field Y': True, 'Field Z': False}, {'Field X': True, 'Field Y': False, 'Field Z': True}, {'Field X': True, 'Field Y': False, 'Field Z': False}, {'Field X': False, 'Field Y': True, 'Field Z': True}, {'Field X': False, 'Field Y': True, 'Field Z': False}, {'Field X': False, 'Field Y': False, 'Field Z': True}, {'Field X': False, 'Field Y': False, 'Field Z': False}]
This is OK as far as it goes when I have (as here) three fields and two values, but it gets hairy when I have dozens of fields with multiple values! I reckon there must be an easy way to do this with itertools but don’t know what that is. Something with itertools.product() maybe?