python - 向嵌套字典添加值的问题
问题描述
我写了一个函数,给定一个数据框,为每一列生成一个分数。我想将此分数添加到表中,该表结构为嵌套字典。问题是当我将分数添加到嵌套字典中的特定键时,它会将此分数添加到具有相同键的整个字典中。特别是这是代码:
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 个词典中。
解决方案
尝试这个:
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
推荐阅读
- ios - 你如何为不同的 iOS 版本提供不同的类声明?
- flutter - Flutter - 如何在 Flutter 中合并两个流?为什么我只有最后一个流?
- python-3.x - 如何在谷歌云控制台中为云功能设置日志文件?
- javascript - 如何确定出现在 Stripe 结帐中的产品的顺序/顺序
- amazon-web-services - 从手动批准步骤将输入传递给 Step Function
- python - RuntimeError: 给定组=1,大小为 [64, 1, 4, 4] 的权重,预期输入 [256, 3, 32, 32] 有 1 个通道,但有 3 个通道
- c# - 在 Azure Functions 中的何处存储共享点路径?
- c++ - 我应该如何在 C/C++ 中计算 GF(2) 上的矩形稀疏矩阵的零空间?
- python - SciPy 最小化算法的比对
- c# - 在 C# 中使用正则表达式查找字符串并用左字符串替换