0

My dictionary is as below

    {
     '34.8': [[0, 0, 0, 0], [0, 0, 0, 0]], 
     '34.6': [[0, 0, 0, 0], [0, 0, 0, 0]],
     '35.0': [[0, 0, 0, 0], [0, 0, 0, 0]], 
     '34.4': [[0, 0, 0, 0], [0, 0, 0, 0]],
     '34.2': [[0, 0, 0, 0], [0, 0, 0, 0]], 
     '34.0': [[0, 0, 0, 0], [0, 0, 0, 0]] 
}

and I run code.

print '34.6', testDic['34.6']
print '34.8', testDic['34.8']

testDic['34.6'][0][0] = 1234

print testDic

but result is

{
'34.8': [[1234, 0, 0, 0], [0, 0, 0, 0]], 
'34.6': [[1234, 0, 0, 0], [0, 0, 0, 0]], 
'35.0': [[1234, 0, 0, 0], [0, 0, 0, 0]], 
'34.4': [[1234, 0, 0, 0], [0, 0, 0, 0]], 
'34.2': [[1234, 0, 0, 0], [0, 0, 0, 0]], 
'34.0': [[1234, 0, 0, 0], [0, 0, 0, 0]]}

why change all dic value ?? and how do I change only 1 (such as '34.6') ??

Yongil
  • 15
  • 2
  • 9
    How did you create your dictionary? Did you put the same list into it multiple times? – khelwood Mar 02 '18 at 09:32
  • 5
    it has to do with the way you created the dictionary. This lists are all actually simply references to the same memory object. – Ma0 Mar 02 '18 at 09:33
  • 7
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Sean Breckenridge Mar 02 '18 at 09:35

1 Answers1

0

As suggested in the comments, you're transforming all the values of the dict because they refer to the same object, in your case a list of lists. Look at this example:

d = dict(zip(keys, [[[0]*4]*2]*len(keys)))
d['34.6'][0][0] = 1234
print d

{'34.0': [[1234, 0, 0, 0], [1234, 0, 0, 0]],
 '34.2': [[1234, 0, 0, 0], [1234, 0, 0, 0]],
 '34.4': [[1234, 0, 0, 0], [1234, 0, 0, 0]],
 '34.6': [[1234, 0, 0, 0], [1234, 0, 0, 0]],
 '34.8': [[1234, 0, 0, 0], [1234, 0, 0, 0]],
 '35.0': [[1234, 0, 0, 0], [1234, 0, 0, 0]]}

In this case, even the single lists are linked and their first value is transformed. Otherwise, if you "force" to create a new list of lists for every key, you can avoid this problem becauce every item of the dictionary is independent.

d = {}
for key in keys:
    d[key] = [[0]*4] + [[0]*4]
d['34.6'][0][0] = 1234

print d

{'34.0': [[0, 0, 0, 0], [0, 0, 0, 0]],
 '34.2': [[0, 0, 0, 0], [0, 0, 0, 0]],
 '34.4': [[0, 0, 0, 0], [0, 0, 0, 0]],
 '34.6': [[1234, 0, 0, 0], [0, 0, 0, 0]],
 '34.8': [[0, 0, 0, 0], [0, 0, 0, 0]],
 '35.0': [[0, 0, 0, 0], [0, 0, 0, 0]]}
el_Rinaldo
  • 970
  • 9
  • 26