首页 > 解决方案 > 向嵌套字典添加值的问题

问题描述

我写了一个函数,给定一个数据框,为每一列生成一个分数。我想将此分数添加到表中,该表结构为嵌套字典。问题是当我将分数添加到嵌套字典中的特定键时,它会将此分数添加到具有相同键的整个字典中。特别是这是代码:

kernel = input("Please enter the kernel you want to use:\n")
score = Kernel_evaluation(Estimators, x, Targets, threshold)
print (f'The score is {score}')
for dict_1 in Scoring:
    if dict_1 == dataframe.columns[x]:
        for KEY in Scoring[dict_1]:
            if KEY == kernel:
                Scoring[dict_1][KEY] = score
                break
            else:
                continue
            break

            else:
                continue

评分是嵌套字典,包含 4 个键(我在数据框中有 4 列),每个键都包含一个带有 6 个键的字典(我有 6 个内核可以使用)。当我将值分数添加到对应键时,它会将我添加到所有 4 个字典中(在我的示例中,内核是高斯的,并且 4 个字典中的每个“高斯”键每次都使用分值进行更新。我不知道为什么会这样。你能帮帮我吗?

样本数据是 iris 数据集,我希望字典字典是这样的:

Scoring = {'sepal_length': {'gaussian': 0.0, 'tophat': 0.0, 'epanechnikov': 0.0, 'exponential': 0.0, 'linear': 0.0, 'cosine': 0.0}, 
           'sepal_width': {'gaussian': 0.0, 'tophat': 0.0, 'epanechnikov': 0.0, 'exponential': 0.0, 'linear': 0.0, 'cosine': 0.0}, 
           'petal_length': {'gaussian': 0.0, 'tophat': 0.0, 'epanechnikov': 0.0, 'exponential': 0.0, 'linear': 0.0, 'cosine': 0.0}, 
           'petal_width': {'gaussian': 0.0, 'tophat': 0.0, 'epanechnikov': 0.0, 'exponential': 0.0, 'linear': 0.0, 'cosine': 0.0}}

但是对于四个字典中的每个键,我想要一个分数(我用另一个函数获得,但它是一个简单的数字)。当我将此分数添加到Scoring[KEY][key]其中时,它将添加到所有 4 个词典中。

标签: pythondictionary

解决方案


尝试这个:

for x in range(0, len(Targets)): 
    for dict_1 in Scoring:
        Estimators = [] Estimators = Kernel_generator(x, Targets, Labels, kernel, Estimators) 
        score = Kernel_evaluation(Estimators, x, Targets, threshold) 
        if dict_1 == dataframe.columns[x] and kernel in Scoring[dict_1]:
            Scoring[dict_1][kernel] = score

推荐阅读