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 hap
The best and the easiest ways to create a copy of a dict in both Python 2.7 and 3 are...
To create a copy of simple(single-level) dictionary:
1. Using dict() method, instead of generating a reference that points to the existing dict.
my_dict1 = dict()
my_dict1["message"] = "Hello Python"
print(my_dict1) # {'message':'Hello Python'}
my_dict2 = dict(my_dict1)
print(my_dict2) # {'message':'Hello Python'}
# Made changes in my_dict1
my_dict1["name"] = "Emrit"
print(my_dict1) # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2) # {'message':'Hello Python'}
2. Using the built-in update() method of python dictionary.
my_dict2 = dict()
my_dict2.update(my_dict1)
print(my_dict2) # {'message':'Hello Python'}
# Made changes in my_dict1
my_dict1["name"] = "Emrit"
print(my_dict1) # {'message':'Hello Python', 'name' : 'Emrit'}
print(my_dict2) # {'message':'Hello Python'}
To create a copy of nested or complex dictionary:
Use the built-in copy module, which provides a generic shallow and deep copy operations. This module is present in both Python 2.7 and 3.*
import copy
my_dict2 = copy.deepcopy(my_dict1)