Home > Mobile >  Looping over dict without nested for loops
Looping over dict without nested for loops

Time:03-30

I have a dictionary called params. I need to loop over this dict so that it prints every possible combination of learn_rate and btch_size in order. Here is my dict:

params = dict(
    learn_rate = [0.01, 0.001, 0.0001]
    ,btch_size = [50, 70, 80]

)

desired output:

0.01 50
0.01 70
0.01 80
0.001 50
0.001 70
0.001 80
0.0001 50
0.0001 70
0.0001 80

I was considering using itertools for this as I do not want loads of nested for loops incase I decide to add new lists. Does anyone have any suggestions?

CodePudding user response:

'itertools.product()' does exactly that. Works with as many lists as you want to add.

>>> list(itertools.product(*params.values()))
[(0.01, 50), (0.01, 70), (0.01, 80), (0.001, 50), (0.001, 70), (0.001, 80), (0.0001, 50), (0.0001, 70), (0.0001, 80)]
>>>
  • Related