创建,混合和匹配任何字典

时间:2018-10-08 15:11:29

标签: python dictionary

我有输入数据

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

我想创建一个混合搭配,如下:

[ {'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'}]

1 个答案:

答案 0 :(得分:4)

您可以使用itertools.product生成值的组合,然后将其重新构建为字典:

from itertools import product

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

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

打印

[{'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'}]