Python Forum
Appending object to 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: Appending object to array (/thread-27547.html)



Appending object to array - Busby - Jun-10-2020

I'm trying to append objects to an array with the following code

    model_array = [model 1, model 2, model 3]
    json_array = []
    model_data = {}

    X = len(model_array)
    Y = 0

    while Y != X:
        model_data["label"] = 'Model No'
        model_data["value"] = model_array[Y]
        json_array.append(model_data)
        Y = Y + 1

    print(json_array) 
The output of the json_array is
Output:
{ label : Model No value : model 3 } { label : Model No value : model 3 } { label : Model No value : model 3 }
Can anybody tell me why the json_array only lists model 3 and not the other models


RE: Appending object to array - Yoriz - Jun-10-2020

The same dictionary is being added to the list 3 times.
Note line 1 is not valid code.


RE: Appending object to array - deanhystad - Jun-10-2020

As Yoriz says, you are adding the same dictionary each time. If you were to do this:
for thing in json_array:
    print(id(thing))
It would print the same ID for each item. So when you change the contents of "model_data" the last time through the loop, that is what shows up as values for each (each and only) thing in json_array.

To get different contents you need to make different containers.
model_array = [model_1, model_2, model_3]
json_array = []
 
X = len(model_array)
Y = 0
 
while Y != X:
    model_data["label"] = 'Model No'
    model_data["value"] = model_array[Y]
    json_array.append({'label':'Model No', 'value':model_array[Y]}) # New dictionary each time
    Y = Y + 1
 
print(json_array)
But this is awkward code and can be done in a cleaner, shorter and more efficient way.
model_array = [model_1, model_2, model_3]
json_array = []
for model in model_array:
    json_array.append({'label':'Model No', 'value':model})
print(json_array)
Or even as a list comprehension
model_array = [model_1, model_2, model_3]
json_array = [{'label':'Model No', 'value':model} for model in model_array]
print(json_array)