Producing all possible permutations from a dict + list

Viewed 49

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?

1 Answers

Use itertools.product(values, repeat=3) to get every combination of 3 values.

variants = [{
    'Field X': x,
    'Field Y': y,
    'Field Z': z,
} for x in values for y in values for z in itertools.product(values, repeat=3)]

If you have a dynamic list of fields, you can create the dictionary dynamically using dict(zip(...))

values=[True, False]
fields=['Field X', 'Field Y', 'Field Z']
variants = [
    dict(zip(fields, values))
    for values in itertools.product(values, repeat=len(fields))
]
Related