0

I have this code

DATA = [
{"Value":0}
]

dicDATA = {"Value":0}

var = 0

#in some function...
print("Insert a value:")
var = int(input())

dicDATA["Value"] = var
DATA.append(dicDATA)

for i in DATA:
    print(i["Value"])

If i insert a value 2 ,I expect the output to be 2 and it's ok but if i insert another value 5 , I expect the output of:

2
5

But the actual output is:

5
5

The value gets overwritten

  • It's likely you're inserting the same variable - not just the same *value*, but the same *variable* - every time. When you change the value of that variable, it also changes for everything else that looks at it - because each index of the list is looking at the same thing, they all report seeing the same thing. – Green Cloak Guy Jun 17 '19 at 21:34
  • 1
    @GreenCloakGuy No, *variables* are not inserted into lists, *objects* are. The issue is that the same object (in this case a dictionary) is being added to the list multiple times. – khelwood Jun 17 '19 at 21:44

1 Answers1

0

You're not making a copy of dicData every time you append it. So you're appending the same dictionary every time.

You should create a new dictionary each time you append.

print("Insert a value:")
var = int(input())

dicDATA = {"Value": var}
DATA.append(dicDATA)
Barmar
  • 741,623
  • 53
  • 500
  • 612