I have this piece of code:
import json a = ''' { "c": { "d": [ { "e": "f" } ] } } ''' j = json.loads(a) l = [] for n in range(20): if n % 2 == 0: j['c']['d'][0]['e'] = n l.append(j) print(l)
The output of this code:
[{'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}, {'c': {'d': [{'e': 18}]}}]
The output I was expected:
[{'c': {'d': [{'e': 0}]}}, {'c': {'d': [{'e': 2}]}}, {'c': {'d': [{'e': 4}]}}, {'c': {'d': [{'e': 6}]}}, {'c': {'d': [{'e': 8}]}}, {'c': {'d': [{'e': 10}]}}, {'c': {'d': [{'e': 12}]}}, {'c': {'d': [{'e': 14}]}}, {'c': {'d': [{'e': 16}]}}, {'c': {'d': [{'e': 18}]}}]
How to get the expected output?
Advertisement
Answer
When you modify j
and subsequently append it to the l
, it’s a reference to the same dict that you append. Here is one way to operate on copies:
import copy import json a = ''' { "c": { "d": [ { "e": "f" } ] } } ''' j = json.loads(a) l = [] for n in range(10): j2 = copy.deepcopy(j) j2['c']['d'][0]['e'] = 2 * n l.append(j2) print(l)