单项列表字典转换成值字典

时间:2018-07-13 20:06:31

标签: python list dictionary

当我使用以下方式检索Hyperopt试用版时

my_trial = trials.trials[n]['misc']['vals'] 

我得到了一个字典,由每个元素的列表组成。

{   'base_score': [0.5],
    'colsample_bylevel': [0.5],
    'colsample_bytree': [0.7000000000000001],
    'learning_rate': [0.2],
    'max_depth': [10.0],
    'min_child': [80.0],
    'min_split_loss': [0.8],
    'n_estimators': [500.0],
    'norm': [1],
    'norm_norm': [2],
    'quant_distr': [],
    'scale': [3],
    'scale_pos_w': [3.1],
    'subsample': [0.8]}

但是,为了使用space_eval(space,my_trial),我需要一个字典,其中的值是上面列表的元素,而不是列表。

实际上是当我使用获得的“最佳”检索最佳试用版时

{   'base_score': 0.8,
    'colsample_bylevel': 0.8,
    'colsample_bytree': 0.5,
    'learning_rate': 0.5,
    'max_depth': 11.0,
    'min_child': 90.0,
    'min_split_loss': 0.4,
    'n_estimators': 100.0,
    'norm': 1,
    'norm_norm': 2,
    'scale': 3,
    'scale_pos_w': 7.2,
    'subsample': 0.5}

可用于通过

实例化“空间”中的相应点
point = space_eval(space, my_trial)

如果可能的话,我想用一条简单的直接指令将第一个字典转换成第二个字典

非常感谢!

2 个答案:

答案 0 :(得分:5)

您可以使用字典理解:

d = {k: v[0] for k, v in d.items() if v}

答案 1 :(得分:0)

您可以通过dict comprehension转换此示例(空列表将转换为n.children[0]):

None

输出:

my_dict = {   'base_score': [0.5],
    'colsample_bylevel': [0.5],
    'colsample_bytree': [0.7000000000000001],
    'learning_rate': [0.2],
    'max_depth': [10.0],
    'min_child': [80.0],
    'min_split_loss': [0.8],
    'n_estimators': [500.0],
    'norm': [1],
    'norm_norm': [2],
    'quant_distr': [],
    'scale': [3],
    'scale_pos_w': [3.1],
    'subsample': [0.8]}

new_dict = {k:v[0] if len(v) > 0 else None for k, v in my_dict.items()}

print(new_dict)