Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

Can someone please explain this to me? This doesn't make any sense to me.

I copy a dictionary into another and edit the second and both are changed. Why is this happening?

>>> dict1 = {"key1": "value1", "key2": "value2"} 

>>> dict2 = dict1 

>>> dict2 

{'key2': 'value2', 'key1': 'value1'}

>>> dict2["key2"] = "WHY?!"

>>> dict1 

{'key2': 'WHY?!', 'key1': 'value1'}

1 Answer

0 votes
by (106k points)

When you set dict2 = dict1, you are making them refer to the same exact dict object because Python never implicitly copies objects. So when you mutate it, all references to it keep referring to the object in its current state.

To copy the dictionary you need to do it explicitly like as follows:-

dict2 = dict(dict1)

or

dict2 = dict1.copy()

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...