Copying dictionaries containing lists

Harald Massa cplx.12.ghum at spamgourmet.com
Fri Mar 21 10:29:43 CET 2003


I read about dictionaries:

"""If you want to modify a dictionary and keep a copy of the original,
use the copy method. For example, opposites is a dictionary that
contains pairs of opposites:

>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} 
>>> alias = opposites 
>>> copy = opposites.copy() 
""" (1)


and than I did the following:


ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on
Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> karl={'int':[],'rep':[]}
>>> mirja=karl.copy()
>>> print karl
{'int': [], 'rep': []}
>>> print mirja
{'int': [], 'rep': []}

#.... Now mirja should be a copy of karl, should'nt it? 

>>> karl["rep"].append("Something special")
>>> print karl
{'int': [], 'rep': ['Something special']}

#works as expected... but:

>>> print mirja
{'int': [], 'rep': ['Something special']}
#Not at all expected. Hot did "Something special" get to mirja?


#Let's put in tanja:
>>> tanja={'int':[],'rep':[]}

#And append interisting things to karl
>>> karl["int"].append("Nothing usual")

>>> print karl
{'int': ['Nothing usual'], 'rep': ['Something special']}
#as expected.
>>> print mirja
{'int': ['Nothing usual'], 'rep': ['Something special']}
#the same problem again.

>>> print tanja
{'int': [], 'rep': []}
# only tanja is a good girl.

What is going wrong? What did I misunderstand?

Harald



# (1) excerpt from "how to think like a computer scientist using
python"




More information about the Python-list mailing list