Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Appending object to array
#1
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
Reply
#2
The same dictionary is being added to the list 3 times.
Note line 1 is not valid code.
Reply
#3
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  accessing value array object ortollj 1 1,564 Aug-30-2020, 12:00 PM
Last Post: ortollj

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020