I have this piece of code:
JavaScript
x
23
23
1
import json
2
3
a = '''
4
{
5
"c": {
6
"d": [
7
{
8
"e": "f"
9
}
10
]
11
}
12
}
13
'''
14
j = json.loads(a)
15
l = []
16
17
for n in range(20):
18
if n % 2 == 0:
19
j['c']['d'][0]['e'] = n
20
l.append(j)
21
22
print(l)
23
The output of this code:
JavaScript
1
2
1
[{'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}]}}]
2
The output I was expected:
JavaScript
1
2
1
[{'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}]}}]
2
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:
JavaScript
1
23
23
1
import copy
2
import json
3
4
a = '''
5
{
6
"c": {
7
"d": [
8
{
9
"e": "f"
10
}
11
]
12
}
13
}
14
'''
15
j = json.loads(a)
16
l = []
17
for n in range(10):
18
j2 = copy.deepcopy(j)
19
j2['c']['d'][0]['e'] = 2 * n
20
l.append(j2)
21
22
print(l)
23