d1 = {"dog":"woof", "cat":"meow"}
d2 = d1
d2["dog"] = "bark"
for i in d1:
print(i, d1[i])
dog bark
cat meow
What's the best way to do it so:
dog woof
cat meow
d1 = {"dog":"woof", "cat":"meow"}
d2 = d1.copy() # make a copy, not a reference to the same dictionary
d2["dog"] = "bark"
for i in d1:
print(i, d1[i])
# dog woof
# cat meow
d1 and d2 point to the same object in the memory and therefore changing values in d2 will affect d1 as well.
d1 = {}
d2 = d1
print id(d1) == id(d2)
# out: True
Use the copy-method of the dictionary-class or the copy-module.
d2 = d1.copy()
from copy import copy
d2 = copy(d1)
If you have mutable objects stored in the dictionary (i.e. lists) and want to copy theese as well, you should use the deepcopy-function.
from copy import deepcopy
d2 = deepcopy(d1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With