[英]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 ?? 为什么更改所有dic值? and how do I change only 1 (such as '34.6') ??
以及如何只更改1(例如“ 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. 如注释中所建议,您正在转换dict的所有值,因为它们引用的是同一对象,在您的情况下为列表列表。 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]]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.