(I hope this question hasn't been answered elsewhere - it was difficult to search for this particular issue.)
When I iterate over a list of dictionaries, and I add an entry to ONE of the dictionaries, it seems to be added to ALL of them.
#!/usr/bin/python
dicLs = [{}] * 2
n = 0
nn = 10
for i in range(len(dicLs)):
print "assigning dicLs[", i, "][", n, "] = ", nn
dicLs[i][n] = nn
n += 1
nn += 10
for i in range(len(dicLs)):
print "\ni", i
for key in dicLs[i].keys():
print "dicLs[", i, "][", key, "] = ", dicLs[i][key]
Output:
assigning dicLs[ 0 ][ 0 ] = 10
assigning dicLs[ 1 ][ 1 ] = 20
i 0
dicLs[ 0 ][ 0 ] = 10
dicLs[ 0 ][ 1 ] = 20
i 1
dicLs[ 1 ][ 0 ] = 10
dicLs[ 1 ][ 1 ] = 20
The only way I can figure out to get around this is to make a copy of the dictionary, then add the entry, then copy the dictionary back to the list:
#!/usr/bin/python
dicLs = [{}] * 2
n = 0
nn = 10
for i in range(len(dicLs)):
print "assigning dicLs[", i, "][", n, "] = ", nn
# Convoluted workaround
newDic = dicLs[i].copy()
newDic[n] = nn
dicLs[i] = newDic.copy()
n += 1
nn += 10
for i in range(len(dicLs)):
print "\ni", i
for key in dicLs[i].keys():
print "dicLs[", i, "][", key, "] = ", dicLs[i][key]
Output:
assigning dicLs[ 0 ][ 0 ] = 10
assigning dicLs[ 1 ][ 1 ] = 20
i 0
dicLs[ 0 ][ 0 ] = 10
i 1
dicLs[ 1 ][ 1 ] = 20
Does anyone know why this is or how to fix it?
Thanks!
Jeremy.