I'm struggling with dictionaries
dic1 = {"A":"a","B":"b","C":"c"}
dic2 = dic1
dic2["D"]="d"
print(dic1)
output:
{'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
Could someone explain me why dic1 also appended "D" key with "d" value? And what can I do to avoid this problem? I really want dic1 to not change values
CodePudding user response:
This is happening because you're working with references. This guide is a great explanation of Python references.
To avoid this problem, try the following:
dic1 = {"A":"a","B":"b","C":"c"}
dic2 = dic1.copy()
CodePudding user response:
This is the fundamental property of Python objects. When you naively assign an existed object to a new one, the new one actually points to the first object.
With dict2 = dict1
, you are actually pointing to the same object. That means every change you make in dict2
will affect the original object.
In case you want to copy a dictionary, try dict2 = dict(dict1)
.