Python Forum

Full Version: Dict overwrite previous list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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']}}
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'.