[英]Python Nested Dict how to independently update value
我有一个具有相似值的嵌套字典:
{'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()
这dict
您如何为dict
键分配值。 显然你有类似以下情况:
class_grades = {"Arithmancy": 0.0, "Astronomy": 0.0, ...}
thetas = {"Gryffindor": class_grades, "Hufflepuff": class_grades, ...}
无论您已经到达那里,当您访问/修改thetas["Gryffindor"]
,它与引用的对象/实例完全相同: thetas["Hufflepuff"]
。 也就是说,这dict
您最初如何填充dict
。 您可以通过询问每个嵌套dict
id()
来验证假设:
print([id(i) for i in thetas.values()])
唯一实例具有唯一 ID。 相同的对象/实例报告相同的 id。
如果您想拥有初始值的dict
,然后填充每个“房子”,您可以实例化一个新的字典(具有相同的值)...在这种情况下(无需进一步嵌套),只需调用dict()
就足够了,例如:
class_grades = {"Arithmancy": 0.0, "Astronomy": 0.0, ...}
thetas = {"Gryffindor": dict(class_grades),
"Hufflepuff": dict(class_grades), ...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.