Problem with Json Array - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Problem with Json Array (/thread-34456.html) |
Problem with Json Array - kwekey - Aug-02-2021 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 RE: Problem with Json Array - deanhystad - Aug-02-2021 This does not give you three dictionaries. It gives you 1 dictionary three times. b = [{"arrayA":1, "arrayB":6}] * 3Essentially 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 RE: Problem with Json Array - kwekey - Aug-02-2021 Thanks Dean, That's sounds logical. I recode accordingly and try again. |