newbie: copying dictionaries

Jon J. Morin rotundo52 at hotmail.com
Wed Jun 12 01:18:57 EDT 2002


Jon J. Morin wrote:

> Hi.  I'm a newbie to python and have a question about copying dictionary
> objects.  I'm working out of Learning Python by Mark Lutz & David Ascher
> (O'Reilly).  The following bit of code was an exercise in the book and it
> works, but what I'm asking is why?  I see where the dictionary keys get
> copied from one object to the other, but how do the values get copied over
> as well?
> 
> #!/usr/bin/python
> # copyDict.py - copy a dictionary argument and return it
> 
> def copyDict(aDict):
>     newDict = {}
>     for key in aDict.keys():
>         newDict[key] = aDict[key]
>     return newDict
> 
> D = {'jon':1, 'allison':2, 'zachary':3}
> print copyDict(D)
> 
> Output:
> [jmorin at cisx1 python]$ ./copyDict.py
> {'zachary': 3, 'jon': 1, 'allison': 2}
> 
> Any help with this is appreciated.  Thanks.
> 
> Jon J. Morin
Thanks, guys.  I think that I understand this now.  Thanks for the help.

Jon



More information about the Python-list mailing list