简体   繁体   中英

Python 2.7 list change in dictionary

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') ??

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]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM