S rick S rick - 5 months ago 8
Python Question

How can i add a list to a list in a dictionary

I'm struggling to figure out whats going wrong here I'm trying to append this list to a dictionary key's list but I only ever get the last one.

For example:

pastmoves =['n','w','s','w']
moves = [1,0,1,0]
turnpt = {'pos' : [],
'moves' : [],
'lastmove' : []}
pos = [1,1]
opt = [1]


while 5 not in opt:
if len(pastmoves) > 1:
if moves.count(1) > 1:
if pos not in turnpt['pos']:
turnpt['pos'].append(pos)
print(turnpt['pos'])
pos[1] += 1
print(pos)
opt[0] += 1
else:
print(opt)


My stdout reads:

[[1, 1]]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[5]


I'm expecting each version of
pos
to be appended to the
turnpt['pos']
list, but that doesn't happen, why is this?

Note:

My if logic is nested because there are other actions I need to complete in between each one, this is just a working example.

Answer

Pass a copy of the list pos using pos[:]. When you append pos and then change it, it will also be changed in turnpt because it is a reference to a list and your condition will never be True.

while 5 not in opt:
    if len(pastmoves) > 1:
        if moves.count(1) > 1:
            if pos not in turnpt['pos']:
                turnpt['pos'].append(pos[:])
                print(turnpt['pos'])
Comments