0

Thanks for taking your time to read my issue.

I have a coding scenario were I have an original dictionary. I set that original dictionary into a new variable, which from my understanding is spawning a clone of that object.

When I create a second dictionary, and use the update function of the new dict to merge the second dict, it updates the original dict and the new dict. I expect it to only update the new variable dict while perserving the original dict.

See a code example below:

dict1 = {"main": "test1"}
dict2 = {"sub": "test2"}
dict_combo = dict1
dict_combo.update(dict2)
print(dict1)
print(dict_combo)

Results:

$ python3 test_dict.py 
{'main': 'test1', 'sub': 'test2'}
{'main': 'test1', 'sub': 'test2'}

What I expect to see:

$ python3 test_dict.py 
{'main': 'test1'}
{'main': 'test1', 'sub': 'test2'}

As you can see, both dict1 and dict_combo are being updated when I am only updating the dict object called dict_combo.

Can someone explain why my expectation is wrong? Why is dict1 being updated?

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Shinerrs
  • 129
  • 2
  • 13
  • 1
    ``dict_combo = dict1`` creates an alias, not a copy, of ``dict1``. There is only one single ``{"main": "test1"}`` known by two names. – MisterMiyagi Jul 20 '21 at 10:27
  • This is a good reference on how variables work in Python: https://realpython.com/python-variables/#object-references When you assign an object to a "variable" you're really just creating a new pointer to an existing object. Python has no concept of copying on assignment. – Iguananaut Jul 20 '21 at 10:31
  • 1
    Hey! Thank you both for your reply! That explains my misunderstanding. Thanks for the link @Iguananaut – Shinerrs Jul 20 '21 at 10:47

0 Answers0