Python Forum

Full Version: Problem with Json Array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a problem with modifying an array of JSON message.
I created array a and array using 2 different method.
Then I tried to change one of the key value "arrayA" of the first element in both array
While array a gives me the desired result, array b does not.
All the key value "arrayA" in array b has been.

a = [{"arrayA":1, "arrayB":6},{"arrayA":1, "arrayB":6},{"arrayA":1, "arrayB":6}]
a[0]["arrayA"] = 4
print(a)

b = [{"arrayA":1, "arrayB":6}] * 3
b[0]["arrayA"] = 4
print(b)

=============== RESTART: C:/Users/HomeAdmin/Desktop/jsonarray.py ===============
[{'arrayA': 4, 'arrayB': 6}, {'arrayA': 1, 'arrayB': 6}, {'arrayA': 1, 'arrayB': 6}]
[{'arrayA': 4, 'arrayB': 6}, {'arrayA': 4, 'arrayB': 6}, {'arrayA': 4, 'arrayB': 6}]
>>>

Can anyone tell me what is wrong?

TIA
kwekey
This does not give you three dictionaries. It gives you 1 dictionary three times.
b = [{"arrayA":1, "arrayB":6}] * 3
Essentially what you are doing is this:
a = {"arrayA":1, "arrayB":6}
b = [a, a, a]
You could use a comprehension.
b = [{"arrayA":1, "arrayB":6} for _ in range(3)] 
This is not a json thing. It is a characteristic of lists and a very common and confusing Python problem
Thanks Dean,

That's sounds logical.
I recode accordingly and try again.