1

I want to append different values to the same dictionary structure inside a JSON list. Here is an example:

myJson = {"list": []}

element = {"value": []}
myJson["list"].append(element)
myJson["list"].append(element.copy())

myJson["list"][0]["value"].append("first")
myJson["list"][1]["value"].append("second")
print(myJson)

What this prints out is:

{'list': [{'value': ['first', 'second']}, {'value': ['first', 'second']}]}

But I want:

{'list': [{'value': ['first']}, {'value': ['second']}]}

What am I doing wrong? I created a copy of element so why is it still the same? Thanks!

Ruby
  • 413
  • 1
  • 4
  • 16
  • 2
    You need to make a deep copy, `.copy` is only a shallow copy. `import copy` and use `copy.deepcopy` – juanpa.arrivillaga Jul 27 '18 at 18:58
  • 2
    You can also consider a list/dict comprehension `values = ['first', 'second']` and `{'list': [{'value': [v]} for v in values]}` – rafaelc Jul 27 '18 at 19:01
  • It works! Thank you so much. The other answers I found only said to do `element.copy()` so I was confused. – Ruby Jul 27 '18 at 19:03

0 Answers0