I was reading this post and now am trying to create a class to modify a dictionary and store the modified dictionary in a new variable, without any effect on the original dictionary. Here is the code:
dict_1 = {'a':[0,1,2]}
print('dict_1 before updating is :', dict_1)
#################################################
class dict_working:
def __init__(self, my_dict):
self.my_dict = (my_dict)
def update_dict(self):
for i in range(len(self.my_dict['a'])) :
self.my_dict['a'][i] = self.my_dict['a'][i]+10
return self.my_dict
#################################################
obj = dict_working(dict_1)
b_dict = obj.update_dict()
print('dict_1 after updating is :', dict_1)
print('A new object after updating is:', b_dict)
But when I try the code, It also modifies the dict_1
variable:
dict_1 before updating is : {'a': [0, 1, 2]}
dict_1 after updating is : {'a': [10, 11, 12]}
A new object after updating is: {'a': [10, 11, 12]}
So I tried to deepcopy
the dictionary in the class and the results was just as I wanted:
import copy
dict_1 = {'a':[0,1,2]}
print('dict_1 before updating is :', dict_1)
#################################################
class dict_working:
def __init__(self, my_dict):
self.my_dict = copy.deepcopy(my_dict)
def update_dict(self):
for i in range(len(self.my_dict['a'])) :
self.my_dict['a'][i] = self.my_dict['a'][i]+10
return self.my_dict
obj = dict_working(dict_1)
b_dict = obj.update_dict()
#################################################
print('After adding deepcopy method:')
print('dict_1 after updating is :', dict_1)
print('A new object after updating is:', b_dict)
The results are:
dict_1 before updating is : {'a': [0, 1, 2]}
After adding deepcopy method:
dict_1 after updating is : {'a': [0, 1, 2]}
A new object after updating is: {'a': [10, 11, 12]}
My question:
Do Python experts also use the same deepcopy
method in these situations or there are other ways?