【问题标题】:Problems to add value to a nested dictionary向嵌套字典添加值的问题
【发布时间】:2020-05-05 18:33:44
【问题描述】:

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

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

Scoring 是嵌套字典,包含 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 个字典中。

【问题讨论】:

  • 添加样本数据和预期输出
  • 样本数据是 iris 数据集,我希望字典像这样: Scoring = {'sepal_length': {'gaussian': 0.0, 'tophat': 0.0, 'epanechnikov' :0.0,“指数”:0.0,“线性”:0.0,“余弦”:0.0},“sepal_width”:{“高斯”:0.0,“tophat”:0.0,“epanechnikov”:0.0,“指数”: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 个字典中
  • 你能告诉我你要更新哪个键
  • 在那种特殊情况下,我想更新所有高斯键,每个键都有不同的分数,以前产生的。因此,在第一个周期中,它将更新 Scoring['sepal_length']['gaussian'],在第二个周期中,将更新 Scoring['sepal_width']['gaussian'],依此类推。但它会同时使用相同的值更新所有这些

标签: python dictionary


【解决方案1】:

试试这个:

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

【讨论】:

  • 不,它没有用。它再次更新子字典中的所有“内核”键
  • 不,现在也没有
  • @AndreaCicconardi 立即查看
  • 我试过了,但还是不行。它为我提供了更多所需的分值。问题可能与我有更多同名的“内核”键有关?
  • 问题应该与python管理字典有关。实际上,每个“子词典”都不是副本,而是一种链接,因此当它更新一个时,每个子词典都会更新
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2020-06-21
  • 2015-12-31
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多