Newbie Alert:
I’m new to Python and when I’m basically adding values to a dict, I find that when I’m printing the whole dictionary, I get the same value of something for all keys of a specific key.
Seems like a pointer issue?
Here’s a snippet when using the event-based XML parser (SAX):
Basically with every end element of “row”, I’m storing the element by it’s key: self.Id, where self is the element.
def endElement(self, name):
if name == "row":
self.mapping[self.Id] = self
print "Storing...: " + self.DisplayName + " at Id: " + self.Id
You’ll get the value
selffor every single entry inself.mapping, of course, since that’s the only value you ever store there. Did you rather mean to take a copy/snapshot ofselfor some of its attributes at that point, then haveselfchange before it gets stored again…?Edit: as the OP has clarified (in comments) that they do indeed need to take a copy:
or, use
copy.deepcopy(self)ifselfhas, among its attributes, dictionaries, lists etc that need to be recursively copied (that would of course includeself.mapping, leading to rather peculiar results — if the normal, shallowcopy.copyis not sufficient, it’s probably worth adding the special method to self’s class to customize deep copying, to avoid the explosion of copies of copies of copies of … that would normally result;-).