首页 > 解决方案 > 将单项列表字典转换为值字典

问题描述

当我检索 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)

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

非常感谢!

标签: pythonlistdictionary

解决方案


您可以使用字典理解:

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

推荐阅读