0
x = []
a = {'sample': True}
x.append(a)
a["sample"] = False
x.append(a)
print(x)

The current result is [{'sample': False}, {'sample': False}].

I need the response to be [{'sample': True}, {'sample': False}].

I've tried x.update({"sample": False}); same effect.

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
MR Sample
  • 23
  • 6

1 Answers1

2

You are appending the 'pointer' (python object) of dictionary, not a copy.

You can try:

def copyof(dico): return {**dico}
a = {'a':True}
x.append(copyof(a))

It will be Ok

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Henry
  • 469
  • 4
  • 9