0

I have a dictionay that I fill with some values, then append that dictionary to a list and loop over that. The problem is that on each new loop, changing the values of the dictionary (with the same keys on every loop) will also change those values on the dictionaries already added to the list.

Heres my code:

script_dict = {}
script_list = []

while row is not None:
    script_dict['id'] = str(row[0])
    script_dict['name'] = row[1]
    script_dict['desc'] = row[2].decode('UTF-8')
    script_dict['subj'] = row[3]
    script_list.append(script_dict)

    row = db.cur.fetchone() # get new set of items from the db

I do understand that python adds a reference to the list instead of all the values, but how do I get around that, or what should I use instead?

TheEdgeOfRage
  • 565
  • 1
  • 8
  • 21
  • 1
    That's because you're modifying the same dictionary over and over. Initialize script_dict inside the loop. – algrebe Feb 01 '17 at 04:51
  • 2
    After reading the duplicate, note that `script_list.append({'id': str(row[0]), 'name': row[1], …})` would be nice and short here – Ry- Feb 01 '17 at 04:51

0 Answers0