简体   繁体   中英

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']. 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 . 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"] . Ie it's down to how you've initially populated your dict s. You can validate the assumption by asking for id() of each nested dict :

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

Unique instances have unique ids. Same objects / instance report the same 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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