Python Forum
Dict overwrite previous list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Dict overwrite previous list (/thread-16917.html)



Dict overwrite previous list - vincentspm - Mar-20-2019

Temp = {}
Final = {}

OK =['OK','OK']
NOTOK =['NOTOK','NOTOK']

Temp[1] = OK
Final['u1']=Temp

print(Final)

Temp.clear()
Temp[2] = OK
Final['u2']=Temp

print(Final)

Temp.clear()
Temp[3] = NOTOK
Final['u3']=Temp

print(Final)
would like to know why last print out overwrite previous one, need help.

Actual result
{'u1': {1: ['OK', 'OK']}}
{'u1': {2: ['OK', 'OK']}, 'u2': {2: ['OK', 'OK']}}
{'u1': {3: ['NOTOK', 'NOTOK']}, 'u2': {3: ['NOTOK', 'NOTOK']}, 'u3': {3: ['NOTOK', 'NOTOK']}}

Expected result
{'u1': {1: ['OK', 'OK']}}
{'u1': {2: ['OK', 'OK']}, 'u2': {2: ['OK', 'OK']}}
{'u1': {3: ['OK', 'OK']}, 'u2': {3: ['OK', 'OK']}, 'u3': {3: ['NOTOK', 'NOTOK']}}


RE: Dict overwrite previous list - scidam - Mar-20-2019

This is well known feature of Python. Read about mutable and immutable objects in Python. Python dictionaries (and lists) are mutable objects, you can check this out by applying id, e.g.
somewhere after line #14 execute id(Final['u1']) and id(Final['u2']). You will see that these id's are equal each other,
that means the same objects are stored under keys u1 and u2. So, when you change the underlying object, Temp (it is the same for all keys u1, u2, u3), everything 'changes immediately'.