无法正确设置dict中的dict值

时间:2014-10-23 14:07:32

标签: python dictionary types

我无法在嵌套字典中设置单个值,如下所示。通常我只想设置EntireMaze [(0,1)] [' 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}}

4 个答案:

答案 0 :(得分:1)

因为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

答案 1 :(得分:1)

如果嵌套的for循环,问题是最里面的一行:

EntireMaze[(row,col)] = cell

这会将EntireMaze字典中的所有值设置为引用相同的字典 - cell引用的字典。因此,当您稍后更改其中一个条目时,您实际上正在更改所有条目,因为所有字典键都引用相同的dict对象。

如果您希望值为不同的对象,则需要复制 cell字典:

EntireMaze[(row,col)] = dict(cell)

(请注意,这不会复制cell中的任何子对象,但由于cell中没有任何引用对象,因此在这种情况下无关紧要。)

答案 2 :(得分:1)

正如布雷特已经说过: 您将单元格对象存储在字典的每个值中。 您应该只复制字典值。

你可以这样做:

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而打印。

答案 3 :(得分:0)

您将cell对象存储在字典的每个值中。你需要做的是复制它,使它们成为独立的对象。

>>> import copy
>>> for row in range(0,height):
...     for col in range(0,width):
...             EntireMaze[(row,col)] = copy.deepcopy(cell)