1

I have a nested loop, which will assemble all variations of params. the more params, the bigger the nesting will become.

for param1 in [1,2,3]:
    for param2 in [5,10,15]:
        for param3 in [10,11,12]:
            for param4 in [35,36,37]:
                for param5 in [2,4,6]:
                    params  = {
                        'param1': param1,
                        'param2': param2,
                        'param3': param3,
                        'param4': param4,
                        'param5': param5,
                    }
                    run_test(params)

To make the code a bit more readable, want to put all variations into a dict, and then create the loop above. but how to achieve this?

configuration  = {
    'param1': [1,2,3],
    'param2': [5,10,15],
    'param3': [10,11,12],
    'param4': [35,36,37],
    'param5': [2,4,6],
}

Desired output is a list of dicts

[
    {
        'param1': param1,
        'param2': param2,
        'param3': param3,
        'param4': param4,
        'param5': param5,
    },
    { next dict …}
]

The Cartesian product would to work if the input is a list of lists, but i have an input which is a dict of lists Suggestions on how to improove the first solution this are highly welcome

endo.anaconda
  • 2,449
  • 4
  • 29
  • 55
  • 1
    I was going to suggest the same answer that you linked to. Which part of that can't you get to work? – tomjn Jun 09 '21 at 14:22
  • 1
    `list(product(*configuration.values()))` – Chris Jun 09 '21 at 14:22
  • Hello! Please do not self-delete and re-post your question when your [previous question is closed](/questions/67905515/nested-loop-from-dict). If you feel that the suggested duplicate doesn't answer your question, you should explain why in an [edit]. After editing, your post will be automatically queued for re-opening. – Brian61354270 Jun 09 '21 at 14:25
  • i added the desired output, which uses the keys of configuration – endo.anaconda Jun 09 '21 at 14:27
  • @Brian sorry i did this – endo.anaconda Jun 09 '21 at 14:28

1 Answers1

6

You can use still use itertools.product, just zip back the keys and values

import itertools 

configuration  = {
    'param1': [1,2,3],
    'param2': [5,10,15],
    'param3': [10,11,12],
    'param4': [35,36,37],
    'param5': [2,4,6],
}

for i in itertools.product(*configuration.values()):
    params = dict(zip(configuration.keys(), i))
    run_test(params)
tomjn
  • 5,100
  • 1
  • 9
  • 24