Reputation: 4357
I have a dictionary consisting of names and a list in each key,like below:
dict1={}
for i in names:
dict1[i]=[]
Then,I process a csv file and I find the result i need,I append it to the corresponding dictonary value,and I append in a list the name and the dictionary value,like below:
list1=[]
for i2 in data:
total_score=sum(i2[1:4])
dict1[i2[0]].append(total_score)
list1.append([i2[0],dict1[i2[0]]])
If i try to print the elements of the list1,I get the final list for each key,and not the progessive list.
The ending list should be like this:
list1=[[name1,[50]],[name1,[50,60]],[name1,[50,60,0,85]]]
Any ideas?Thanks.
Upvotes: 0
Views: 1119
Reputation: 9912
Unless you will clone your list someway, there will be only one copy of it (in your words, the final one). If I understand what you want, the solution is like
list1=[]
for i2 in data:
total_score=sum(i2[1:4])
templist = dict1[i2[0]][:]
templist.append(total_score)
list1.append([i2[0],templist])
See http://docs.python.org/library/copy.html for more details.
Upvotes: 2
Reputation: 63709
Just change:
list1.append([i2[0],dict1[i2[0]]])
to:
list1.append([i2[0],dict1[i2[0]][:]])
This will copy the current value of the list in dict1, instead of just referencing it.
(I'm guessing that this append used to be a print statement, which would just show the current value of the list in dict1. But when you save it into list1, you save a reference to the list, not a copy of it. The [:]
slice operator makes a copy, so that additional appends to the list for key i2[0]
won't be added to the copy.)
Upvotes: 1