Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Append List Repeats Last Element?

I'm having difficulty figuring out why I get n-th many last elements in my "rows" list repeated in my item_list list? So if my rows is a list of tuples:

(("ID 1", "info1", "description1"), ("ID 2", "info2", "description2"), ... ("ID 14", "info14", "description14"))

And then I were to try to make a list dictionary out of this "rows" list of tuples to using the following code:

item_list = []
info = {}

for row in rows:            
    itemId = row[0]
    itemInfo = row[1]
    itemDesc = row[2]

    info['ID'] = itemId
    info['Info'] = itemId
    info['Description'] = itemDesc

    print info

    item_list.append(info)

print item_list

So if my "rows" list has 14 elements, I'll get the 14th element (last element) in "rows" 14 times in my "item_list" list of dictionaries.

item_list = [{"ID": "ID 14", "Info": "info14", "Description": "description14"}, {"ID": "ID 14", "Info": "info14", "Description": "description14"} ... ] #14 times

The "rows" list is a list of tuples. If I print the "info" dictionary just before appending to the "item_list" I can see each different iteration of my "info" dictionary.

Anyone have any ideas? Thanks in advance.

like image 812
ganicus Avatar asked Jun 24 '14 20:06

ganicus


Video Answer


1 Answers

I think you want to change:

item_list = []
info = {} # <---- Move this to inside the loop.

for row in rows:            
    itemId = row[0]
    itemDesc = row[10]

to:

item_list = []

for row in rows:   
    info = {} # <---- here
    itemId = row[0]
    itemDesc = row[10]
like image 160
Uyghur Lives Matter Avatar answered Sep 20 '22 01:09

Uyghur Lives Matter