我正在向函数提供一个字符串,该函数会逐个字符地读取字符串。根据正在处理的字符,从字典调用 JSON 模板,稍微编辑并保存到最终字典,该字典将被解析为 JSON 并保存。
问题是这个模板字典应该保持不变,但事实并非如此。不知何故,我写入中间变量的值被保存到原始模板字典中,弄乱了我试图保存的后续数据。
我是否遗漏了字典的一些基本概念?这是我第一次如此程度地使用词典,所以我不会感到惊讶。
模板字典:
self.map_legend = {"#": {"Id": 100, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Wall", "PlayerNumber": 0},
"-": {"Id": 200, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Shield", "PlayerNumber": 0},
"x": {"Id": 300, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Alien", "PlayerNumber": 0},
"|": {"Id": 400, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "AlienBullet", "PlayerNumber": 0},
"!": {"Id": 500, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Missile", "PlayerNumber": 0},
"i": {"Id": 500, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Missile", "PlayerNumber": 1},
"M": {"Id": 600, "Alive": False, "X": 0, "Y": 0, "Width": 3, "Height": 1, "Type": "MissileController", "PlayerNumber": 0},
"X": {"Id": 700, "Alive": False, "X": 0, "Y": 0, "Width": 3, "Height": 1, "Type": "AlienFactory", "PlayerNumber": 0},
"A": {"Id": 800, "Alive": False, "X": 0, "Y": 0, "Width": 3, "Height": 1, "Type": "Ship", "PlayerNumber": 0},
"V": {"Id": 800, "Alive": False, "X": 0, "Y": 0, "Width": 3, "Height": 1, "Type": "Ship", "PlayerNumber": 1},
" ": {"Id": 900, "Alive": False, "X": 0, "Y": 0, "Width": 1, "Height": 1, "Type": "Space", "PlayerNumber": 0}}
问题代码:
for char in self.initial_game_map:
if char != "\n":
element = self.map_legend[char]
self.id_counters[char] += 1
element["Id"] = self.id_counters[char] + element["Id"]
element["Alive"] = True
element["X"] = char_counter % self.state_json["Map"]["Height"]
element["Y"] = char_counter / self.state_json["Map"]["Height"]
print self.map_legend[char]
print element
row.append(element)
element = {}
char_counter += 1
else:
self.state_json["Map"]["Rows"].append(row)
row = []
一些输出:
V
{'Width': 3, 'PlayerNumber': 1, 'Y': 1, 'X': 2, 'Type': 'Ship', 'Id': 801, 'Alive': True, 'Height': 1}
{'Width': 3, 'PlayerNumber': 1, 'Y': 1, 'X': 2, 'Type': 'Ship', 'Id': 801, 'Alive': True, 'Height': 1}
#
{'Width': 1, 'PlayerNumber': 0, 'Y': 0, 'X': 18, 'Type': 'Wall', 'Id': 103, 'Alive': True, 'Height': 1}
{'Width': 1, 'PlayerNumber': 0, 'Y': 0, 'X': 18, 'Type': 'Wall', 'Id': 103, 'Alive': True, 'Height': 1}
element
变量的行为符合其预期,但您可以看到 self.map_legend
由于某种原因采用了 element
的值更改 element
后,这不是我想要的。这是怎么回事?
最佳答案
element
和 self.map_legend[char]
指向同一个字典,因此如果您更新 element
,您将更新字典self.map_legend[char]
。您似乎想要一份副本,因此请使用:
element = self.map_legend[char].copy()
Python文档中的引用:https://docs.python.org/2/library/copy.html 。由于字典很浅,所以不需要 .deepcopy()
关于使用中间变量时Python字典发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30614755/