【问题标题】:Python Nested Dict how to independently update valuePython嵌套字典如何独立更新值
【发布时间】:2020-03-30 22:37:59
【问题描述】:

我有一个具有相似值的嵌套字典:

{'Gryffindor': {'Arithmancy': 0.0, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0} 
'Hufflepuff': {'Arithmancy': 0.0, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0}}

我想更新单个值。问题是当我更新 dict['Gryffindor']['Arithmancy'] 时,它也会更新 dict['Hufflepuff']['Arithmancy']。 我真的不知道为什么。

我用这个:

thetas["Gryffindor"]["Arithmancy"] = 12

我得到了这个结果:

{'Gryffindor': {'Arithmancy': 12, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0} 
'Hufflepuff': {'Arithmancy': 12, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0}}

有什么想法吗?

编辑:

感谢您的回复,这是我使用的循环:

thetas =  {'Gryffindor': {'Arithmancy': 0.0, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0} 
'Hufflepuff': {'Arithmancy': 0.0, 'Astronomy': 0.0, 'Herbology': 0.0, 'Defense Against the Dark Arts': 0.0}}

for _, house in thetas.items():                 
    for k, v in house.items():
        house[k] = 0.1
     print(thetas)
     exit()

【问题讨论】:

  • 您介意分享更多代码吗?很难用一行来追溯错误。谢谢!
  • 我无法重现您的错误...您期望发生的是 Python 中的行为。看起来您在字典中的键之间缺少逗号(在“Hufflepuff”之前)。我的猜测是你在别处设置了另一个值。

标签: python dictionary nested


【解决方案1】:

这取决于您如何为 dict 中的键分配值。显然你有类似以下情况:

class_grades = {"Arithmancy": 0.0, "Astronomy": 0.0, ...}
thetas = {"Gryffindor": class_grades, "Hufflepuff": class_grades, ...}

无论您已经到达那里,当您访问/修改thetas["Gryffindor"] 时,它与引用的对象/实例完全相同:thetas["Hufflepuff"]。 IE。这取决于您最初填充dicts 的方式。您可以通过询问每个嵌套 dictid() 来验证假设:

print([id(i) for i in thetas.values()])

唯一实例具有唯一 ID。相同的对象/实例报告相同的 id。

如果你想拥有初始值 dict 然后填充每个“房子”,你可以实例化一个新的 dict(具有相同的值)......在这种情况下(不再嵌套),只需调用 @987654330 @ 就足够了,例如:

class_grades = {"Arithmancy": 0.0, "Astronomy": 0.0, ...}
thetas = {"Gryffindor": dict(class_grades),
          "Hufflepuff": dict(class_grades), ...}

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2019-12-04
    • 2017-04-30
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多