0

I have a dictionary let's say my_dic and I want to append it to a list through a loop modifying the value of my_dic, here is the example and it works by the way:

my_lst = []
my_dic = {
    'hello': 'World'
}
my_lst.append(my_dic)
my_dic = {
    'hello': 'World 2'
}
my_lst.append(my_dic)

and it returns [{'hello': 'World'}, {'hello': 'World 2'}] which is what I want and it works correctly. But there is another place where the same thing doesn't work.

query = """
           SELET * FROM some_table
        """

connection = mysql.connector.connect(user=user, 
                                                password=password,
                                                host=host,
                                                database=database)
cursor = connection.cursor(dictionary=True)
cursor.execute(query)   

rows=cursor.fetchall()


data= []
tempRow = rows[0]

tempRow['RS'] = 'old value'
data.append(tempRow)

tempRow = rows[0]
tempRow['RS'] = '1'
data.append(tempRow)


pp(data)

which returns data like this:

[{'RS': '1'}, {'RS': '1'}]

however, I expect it like this:

[{'RS': 'old value'}, {'RS': '1'}]

Edited: I have removed the loop.

Faizan Ali
  • 973
  • 2
  • 16
  • 32
  • You are creating a new list *each loop iteration*. If you expected a single list with all loop iteration results appended, you would want to create the list *once*, before looping. – Martijn Pieters May 28 '18 at 10:35
  • When you assign `tempRow = rows[0]`, that doesn't make a copy of the dict in `rows[0]`. When you modify `tempRow`, you modify `rows[0]` as well. Use `tempRow = rows[0].copy()` instead. – Aran-Fey May 28 '18 at 10:36
  • @Aran-Fey you are right. How do I make a copy? – Faizan Ali May 28 '18 at 10:37
  • @MartijnPieters Forget about the loop, I have removed that in the question too and tested without loop as well, no luck! – Faizan Ali May 28 '18 at 10:40
  • @Aran-Fey you are right. tempRow = rows[0].copy() , got it, thanks. It worked! – Faizan Ali May 28 '18 at 10:44

0 Answers0