Working with copies of a dictionary

Tobias Pfeiffer me at
Sat Dec 13 00:50:55 CET 2003


Damnit, am I angry! Please look at the following example:

class bla:
	def __init__(self):
		self.ho = {'a': ['b'], 'c': ['b', 'e', 'f', 'd'], 'b': 
['a', 'e', 'f', 'c'], 'e': ['b', 'c', 'g', 'h'], 'd': ['c'], 'g': ['e', 
'h'], 'f': ['b', 'c'], 'h': ['e', 'g']} # shall be an adjacence list of 
a graph...
		self.oha = [('a', 'b'), ('b', 'c'), ('b', 'e'), ('b', 'f'), 
('c', 'd'), ('c', 'e'), ('c', 'f'), ('e', 'g'), ('e', 'h'), ('g', 'h')]
	def do_stuff(self):
		next = self.ho.copy() # HERE!!!
		edges = self.oha[:]
		del next['b']

f = bla()
print f.ho
print f.oha

OK, so the two last lines, what surprising thing give me exactly the 
long dictionary I defined in __init__.


Now you see that I do nothing with the self.* thingies themselves. So 
why in hell do the following two lines give me a different output???

print f.ho
print f.oha

f.oha hasn't changed, but f.ho now lacks the two elements I deleted 
from next with the remove() call, while the 'b' array is still there. 
Now can anyone please explain me why do_stuff() ha changed the 
attributes of the class?? Even the following:

next = {}
for v, e in self.ho.items():
	next[v] = e

, where one can easily see that next does not even have the slightest 
connection to f.ho, changes it!! I am completely desparate, because I 
would just like to work with the copy of that dictionary, without 
deleting the proper one. How can I do such a thing?

Thanks in Advance

please send any mail to botedesschattens(at)web(dot)de

More information about the Python-list mailing list