我无法在嵌套dict中设置单个值,如下所示。通常我只想设置EntireMaze[(0,1)]['east'],但它设置了所有的'east'键。知道吗?
cell = {'east' : 0, 'south' : 0}
EntireMaze = {}
height = 2
width = 3
for row in range(0,height):
for col in range(0,width):
EntireMaze[(row,col)] = cell
print EntireMaze
EntireMaze[(0,1)]['east'] = 1
print EntireMaze
输出为:
>>>
{(0, 1): {'east': 0, 'south': 0}, (1, 2): {'east': 0, 'south': 0}, (0, 0): {'east': 0, 'south': 0}, (1, 1): {'east': 0, 'south': 0}, (1, 0): {'east': 0, 'south': 0}, (0, 2): {'east': 0, 'south': 0}}
{(0, 1): {'east': 1, 'south': 0}, (1, 2): {'east': 1, 'south': 0}, (0, 0): {'east': 1, 'south': 0}, (1, 1): {'east': 1, 'south': 0}, (1, 0): {'east': 1, 'south': 0}, (0, 2): {'east': 1, 'south': 0}}
这是因为EntireMaze
中的每个键都指向相同的cell
。您可以使用以下代码(使用copy
操作):
#!/usr/local/bin/python2.7
import copy
cell = {'east' : 0, 'south' : 0}
EntireMaze = {}
height = 2
width = 3
for row in range(0,height):
for col in range(0,width):
EntireMaze[(row,col)] = copy.deepcopy(cell)
print EntireMaze
EntireMaze[(0,1)]['east'] = 1
print EntireMaze
或者只创建循环中的每个cell
dict,如下所示:
#!/usr/local/bin/python2.7
EntireMaze = {}
height = 2
width = 3
for row in range(0,height):
for col in range(0,width):
EntireMaze[(row,col)] = {'east' : 0, 'south' : 0}
print EntireMaze
EntireMaze[(0,1)]['east'] = 1
print EntireMaze
如果嵌套的for
循环,问题是最里面的一行:
EntireMaze[(row,col)] = cell
这将EntireMaze
字典中的所有值设置为引用相同的字典——cell
引用的字典。因此,当您稍后更改其中一个条目时,实际上是在更改所有条目,因为所有字典键都指向同一个dict
对象。
如果您希望值是不同的对象,则需要复制cell
字典:
EntireMaze[(row,col)] = dict(cell)
(请注意,这不会复制cell
中的任何子对象,但由于cell
中没有任何引用对象,因此在这种情况下无关紧要。)
正如Breet所说:您正在将单元格对象存储在字典的每个值中您应该只复制字典值。
你可以这样做:
EntireMaze[(row,col)] = {'east' : 0, 'south' : 0} #You don't need cell = ... anymore
或在此:
EntireMaze[(row,col)] = {'east' : cell['east'], 'south' : cell['south']}
同样在这条路上:
EntireMaze[(row,col)] = dict(cell)
一个结束提示:使用print()
(带有()),而不是仅仅打印,因为Python 3兼容
您将cell
对象存储在字典的每个值中。你需要做的是制作一个副本,使它们都是独立的对象。
>>> import copy
>>> for row in range(0,height):
... for col in range(0,width):
... EntireMaze[(row,col)] = copy.deepcopy(cell)