When I Assign A Dict To Another Variable, Why Does Python Update Both Dicts?
Solution 1:
By using the dictionary copy
-method. Like so:
>>>a = {'b': 1}>>>c = a.copy()>>>c.update({'b': 2})>>>print a
{'b': 1}
>>>print c
{'b': 2}
>>>
Please note that this is a shallow copy. Thus, if you have mutable objects (dictionaries, lists, etc) in your dictionary, it will copy a reference to those objects. In such cases you should use copy.deepcopy. Example below:
>>>import copy>>>a = {'b': {'g': 4}}>>>c = copy.deepcopy(a)>>>c['b'].update({'g': 15})>>>print a
{'b': {'g': 4}}
>>>print c
{'b': {'g': 15}}
Solution 2:
Obviously your question has been answered. But what might help here is to correct your mental model.
In Python, variables don't store values, they name values. Check out this article for the example of the statue pointing at the hotel.
A quick and easy way to check if you're referencing the same object is to print the ID of the variable:
>>>a = {}>>>b = a>>>print(id(a), id(b))
12345 12345
Solution 3:
Try to:
c = a.copy()
Also see this one: Deep copy of a dict in python
It allows you to copy by value lists inside of your dict
Solution 4:
Both variables a
and c
reference the same dict object, so when you mutate it through the variable c
then the underlying dict object is changed. As a
points to the same object, those changes will be visible from there too.
If you want to have both a
and c
reference a dictionary which are independent of each other, then you need to copy the dictionary, so that you actually receive two separate objects. You can do that by using dict.copy
:
a = {'b': 1}
c = a.copy()
c.update({'b': 2})
print a # {'b': 1}
print c # {'b': 2}
Note that this will only create a shallow copy, so if the dictionary contains mutable objects—like another dictionary, a list or some other object—then you all copies will again reference the same underlying objects (just like your original code). If you want to avoid that, you can create a deep copy of the dictionary:
importcopy
a = {'b': {'c': 1}}
b = copy.deepcopy(a)
b['b'].update({'c': 2})
print a # {'b': {'c': 1}}
print b # {'b': {'c': 2}}
Post a Comment for "When I Assign A Dict To Another Variable, Why Does Python Update Both Dicts?"