如何仅将另一个列表中的值添加到字典中

时间:2020-01-17 21:11:28

标签: python list dictionary

我想将 mean_test_score 中的值添加到现有字典中。现有字典如下:

data= [{'C': 0.1, 'gamma': 1, 'kernel': 'linear'},
       {'C': 0.1, 'gamma': 1, 'kernel': 'rbf',},
       {'C': 0.1, 'gamma': 0.1, 'kernel': 'linear'},
       {'C': 0.1, 'gamma': 0.1, 'kernel': 'rbf'},
       {'C': 0.1, 'gamma': 0.001, 'kernel': 'linear'},
       {'C': 0.1, 'gamma': 0.001, 'kernel': 'rbf'},
       {'C': 0.1, 'gamma': 0.0001, 'kernel': 'linear'},
       {'C': 0.1, 'gamma': 0.0001, 'kernel': 'rbf'}]

我的钥匙是固定的。这是一个名为 mean_test_score 的字符串。我的 mean_test_score 看起来像这样:

mean_test_score= {0.92173913, 0.60434783, 0.92173913, 0.60496894, 0.92173913,
       0.71863354, 0.92173913, 0.70993789, 0.92732919, 0.67298137,
       0.92732919, 0.72515528, 0.92732919, 0.78074534, 0.92732919,
       0.73664596, 0.92484472, 0.68478261, 0.92484472, 0.73726708,
       0.92484472, 0.85776398, 0.92484472, 0.83975155, 0.91273292,
       0.68478261, 0.91273292, 0.73571429, 0.91273292, 0.87670807,
       0.91273292, 0.88167702, 0.91024845, 0.68478261, 0.91024845,
       0.73540373, 0.91024845, 0.88074534, 0.91024845, 0.89161491}

因此,在字典 data 中的内核之后,我想添加key = 'mean_test_score'和值,这些值应通过m ean_test_score 进行迭代并添加。我尝试了一些解决方案,但是它们没有用。

所需的输出是

data= [{'C': 0.1, 'gamma': 1, 'kernel': 'linear','mean_test_score': 0.92173913 },
       {'C': 0.1, 'gamma': 1, 'kernel': 'rbf','mean_test_score': 0.60434783},
       {'C': 0.1, 'gamma': 0.1, 'kernel': 'linear', 'mean_test_score': 0.92173913},
       and so on ]

2 个答案:

答案 0 :(得分:2)

for d, m in zip(data, mean_test_score):
    d['mean_test_score'] = m

答案 1 :(得分:1)

假设您的mean_test_score是列表,而不是问题中提到的字典。

不确定这是否是您要寻找的东西

mean_test_score = list(mean_test_score)
count = 0
for i in data:
    i['mean_test_score'] = mean_test_score[count]
    count += 1