-3

I have a input data

block = {
    'kernel' : [3,5,7],
    'strides' : [2,3],
    'padding': ['same'],
    'activation':['relu'],
    'type':['conv'],
}

I would like to create a mix and match follow:

[ {'kernel': 3 ,'strides' : 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
  {'kernel': 3 ,'strides' : 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
  {'kernel': 5 ,'strides' : 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
  {'kernel': 5 ,'strides' : 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
  {'kernel': 7 ,'strides' : 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
  {'kernel': 7 ,'strides' : 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}]
  • what is `count` and `hyperparam`? If `activation` has another item in the list are there even more possibilities? – depperm Oct 08 '18 at 15:17
  • Hello, Chakkrit, I've never had to do this, the answer they gave you looks pythonic and simple. Next time you do a question, try and describe a little bit more, your problem, considering the data structures you use, and what you've tried, that could help anyone that answers, more, because they don't need to analyze a bunch of code as deep, and instead worry more about, the concept that the explain. Great question, and Welcome. – ekiim Oct 08 '18 at 15:24
  • **How** does it not work? Any error messages? – martineau Oct 08 '18 at 15:38
  • @ekiim Thank you so much, Next time, I will be doing to your recommendation. – Chakkrit Termritthikun Oct 08 '18 at 18:44

1 Answers1

4

You can use itertools.product to generate the combinations of values, then build those back into dictionaries:

from itertools import product

keys, possible_values = zip(*block.items())

res = [dict(zip(keys, vals)) for vals in product(*possible_values)]
print(res)

prints

[{'kernel': 3, 'strides': 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
 {'kernel': 3, 'strides': 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
 {'kernel': 5, 'strides': 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
 {'kernel': 5, 'strides': 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
 {'kernel': 7, 'strides': 2, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}, 
 {'kernel': 7, 'strides': 3, 'padding': 'same', 'activation': 'relu', 'type': 'conv'}]
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
  • 1
    `keys, possible_values = zip(*block.items())` looks redundant when we have `dict.keys`/`dict.values` methods – Azat Ibrakov Oct 08 '18 at 15:34
  • @AzatIbrakov I can never remember if `keys()` and `values()` have the same order. [It looks like they do](https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order), so you're right that would be better – Patrick Haugh Oct 08 '18 at 16:49