Home > OS >  Why don't the lists get inserted correctly into my dictionary?
Why don't the lists get inserted correctly into my dictionary?

Time:03-05

a should be [-1,-1,-1], b should be [-1,-1,0] ... z should be [1,1,0] and lastly should be [1,1,1]. When print(i, "is: ", temp) is run through every loop the correct answer gets shown, but when I print the dictionary after the loop all the values are [2,-1,-1].

alfabet = "abcdefghijklmnopqrstuvwxyz "

alfabetKod = {}


temp = [-1,-1,-1]

for i in alfabet:
    print(i, "is: ", temp)
    alfabetKod.setdefault(i, temp)
    

    if temp[2] == 1:
        temp[2] = -1
        if temp[1] == 1:
            temp[1] = -1
            temp[0]  = 1
        else:
            temp[1]  = 1
    else:
        temp[2]  = 1
    
        
    
print(alfabetKod)

CodePudding user response:

You're writing only a reference to the list into your dict, not the current values. Try changing alfabetKod.setdefault(i, temp) to alfabetKod.setdefault(i, temp.copy()) to write the values instead of a reference.

  • Related