1

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

  • `dicts = [{} for _ in range(2)]` (or `[{}, {}]` if you just need two). – timgeb May 25 '17 at 13:44
  • By the way you did write a very good first question, not finding the duplicate when not knowing what to search for is understandable. – timgeb May 25 '17 at 13:50
  • Aaah, so it was in the dictionary declaration. Thank you so much for the quick and perfect reply! – Jeremy Eliosoff May 25 '17 at 14:03
  • Being precise, you only ever created *one* dictionary and put references to the same dictionary into a list of length two. – timgeb May 25 '17 at 14:11

0 Answers0