Python Forum
Dict overwrite previous list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dict overwrite previous list
#1
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']}}
Reply
#2
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'.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to write/overwrite data in a txt. file according to inp Quinn 2 1,587 Aug-12-2025, 04:20 PM
Last Post: Quinn
  Openpyxl overwrite Linechart SamLiu 0 2,244 Nov-26-2022, 05:44 AM
Last Post: SamLiu
  Membership test for an element in a list that is a dict value for a particular key? Mark17 2 2,593 Jul-01-2022, 10:52 PM
Last Post: Pedroski55
  Are list/dict comprehensions interpreted really sequentially? anata2047 3 2,993 May-31-2022, 08:43 PM
Last Post: Gribouillis
  Updating nested dict list keys tbaror 2 2,515 Feb-09-2022, 09:37 AM
Last Post: tbaror
  What type of *data* is the name of a list/tuple/dict, etc? alloydog 9 7,383 Jan-30-2021, 07:11 AM
Last Post: alloydog
Question dict value, how to change type from int to list? swissjoker 3 4,244 Dec-09-2020, 09:50 AM
Last Post: perfringo
  Overwrite previous live data. Makada 2 3,760 Nov-07-2020, 07:40 PM
Last Post: Makada
  How to remove dict from a list? Denial 7 5,617 Sep-28-2020, 02:40 PM
Last Post: perfringo
  Trouble with converting list , dict to int values! faryad13 7 6,389 Sep-04-2020, 06:25 AM
Last Post: faryad13

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020