dictionary - Python dict of dict setting values missmatch -


hi can explain why have following behavior:

>>> k = [0.5, 1, 2] >>> m = [0.5, 1, 2] >>> dict1 = dict.fromkeys(k, dict.fromkeys(m, 0)) >>> dict1 {0.5: {0.5: 0, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}} >>> dict1[0.5][0.5]= 4.5 >>> dict1 {0.5: {0.5: 4.5, 1: 0, 2: 0}, 1: {0.5: 4.5, 1: 0, 2: 0}, 2: {0.5: 4.5, 1: 0, 2: 0}}   >>> dict2 = {0.5: {0.5: 0, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}} >>> dict2[0.5][0.5] = 4.5 >>> dict2 {0.5: {0.5: 4.5, 1: 0, 2: 0}, 1: {0.5: 0, 1: 0, 2: 0}, 2: {0.5: 0, 1: 0, 2: 0}} 

so in first case whenever try change value of dict1 values same second key changing (e.g dict1[0.5][0.5]=4.5 change dict1[1][0.5] reason).

only 1 sub-dictionary ever created. have dictionary accessible in multiple ways. dict[0.5] , dict[1] refer same dictionary (and not copies of it).

one way achieve want use dict comprehension:

dict1 = {k_outer: {k_inner:0 k_inner in m} k_outer in k} 

this creates new nested dict each key, thereby avoiding problem of them accessing same nested dict.


Comments