简体   繁体   中英

Python:how do you append the value of a dictionary key in a list and not the reference?

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.

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM