【发布时间】: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