Ryan Strunk wrote:
Hello everyone,
How can I make two copies of a dictionary that don't point to the same
location in memory? My plan is to generate d1 and make d2 a copy of d1.
After the user modifies d1 I want him/her to be able to return to the
initial dictionary (d2) values. I tried:
d1 = {values}

That can't work, because that makes a set, not a dict (in Python 3 at least). Perhaps you mean {key: value}, not just {value}?

d2 = dict(d1)
then later in the code when I want to re-initialize d1:
d1 = dict(d2)
but this won't work. Any suggestions you have as to how I can make this work
are welcome.

Define "this won't work". What makes you think it doesn't work? This makes d2 a copy of d1, then makes d1 a copy of d2. They are different dicts.

My *guess* is that you're modifying the objects *inside* d1 and d2, which are shared. To make copies of *everything*, all the way down, use the copy module:

copy.copy  # makes a shallow copy, one level only
copy.deepcopy  # makes a deep copy, all the way down


--
Steven

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to