Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Dictionaries linked data

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
like image 296
Spencer Dupre Avatar asked Jun 06 '26 04:06

Spencer Dupre


2 Answers

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
like image 125
jtbandes Avatar answered Jun 07 '26 17:06

jtbandes


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)
like image 35
Niklas R Avatar answered Jun 07 '26 17:06

Niklas R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!