Home > OS >  Why is my object being duplicated when I try to add it to an array?
Why is my object being duplicated when I try to add it to an array?

Time:03-19

I'm using the following to loop through some returned SQL data that has two fields.

cont = []
datarow = {}

for x in result:
    input = x[0]
    response = x[1]

    datarow['input'] = input
    datarow['response'] = response
    print(datarow)
    cont.append(datarow)

The result is

{'input': 'do you have a pet?', 'response': 'yes, I have a dog'}
[{'input': 'do you have a pet?', 'response': 'yes, I have a dog'}]
{'input': "What is your dog's name?", 'response': 'Ringo'}
[{'input': "What is your dog's name?", 'response': 'Ringo'}, {'input': "What is your dog's name?", 'response': 'Ringo'}]

The eventual format is correct, but the data is not. I was expecting to have an array with two objects in it, the two questions and answers.

CodePudding user response:

Each time the for loop runs, you assign the new item to the datarow dictionary and the whole datarow to the cont list. It would be best if you did something like:

cont = []

for x in result:
  datarow = {}
  myInput = x[0]
  response = x[1]
  
  datarow['input'] = myInput
  datarow['response'] = response
  cont.append(datarow)

A side note: never use a name that previously has been assigned to an in-built function in python. input is a function that takes input from the user through the console. I have changed its name to myInput in order to avoid any misunderstanding.

  • Related