简体   繁体   English

Python Nested Dict如何独立更新值

[英]Python Nested Dict how to independently update value

I have a nested dict with similar values:我有一个具有相似值的嵌套字典:

{'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}}

I want to update single value.我想更新单个值。 The probleme is when i update dict['Gryffindor']['Arithmancy'] it will also update dict['Hufflepuff']['Arithmancy'].问题是当我更新 dict['Gryffindor']['Arithmancy'] 时,它也会更新 dict['Hufflepuff']['Arithmancy']。 I don't realy know why.我真的不知道为什么。

I use this:我用这个:

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

and i've go this result :我已经得到了这个结果:

{'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}}

Any ideas ?有任何想法吗 ?

EDIT :编辑 :

Thanks for your reply this is the loop i use :感谢您的回复,这是我使用的循环:

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()

This is down to how you've assigned values to keys in dict .dict您如何为dict键分配值。 Apparently you have something like the following situation:显然你有类似以下情况:

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

However exactly you've arrived there, when you access / modify thetas["Gryffindor"] , it's the very same object / instance as the one referred to from: thetas["Hufflepuff"] .无论您已经到达那里,当您访问/修改thetas["Gryffindor"] ,它与引用的对象/实例完全相同: thetas["Hufflepuff"] Ie it's down to how you've initially populated your dict s.也就是说,这dict您最初如何填充dict You can validate the assumption by asking for id() of each nested dict :您可以通过询问每个嵌套dict id()来验证假设:

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

Unique instances have unique ids.唯一实例具有唯一 ID。 Same objects / instance report the same id.相同的对象/实例报告相同的 id。

If you wanted to have initial dict of values and then populate each "house", you could instantiate a new dict (with the same values)... in this case (no further nesting), simply calling dict() would be enough, eg:如果您想拥有初始值的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM