I have the following class that simply create a dictionary of objects for me. Then copy the created dictionary, main_dict
, to a new dictionary second_dic
.
import numpy as np
class MainClass:
def __init__(self):
self.main_dict = dict()
def add(self, k, val):
self.main_dict[k]=val
main_obj = MainClass()
for i in range(1,5):
main_obj.add(k=i, val=np.random.randint(1,10))
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
second_dic = main_obj.main_dict.copy()
print(second_dic)
{1: 1, 2: 2, 3: 7, 4: 7}
It seems Python doesn't support pointers like C . So when I change a value in my second_dic
, the changes won't reflect in my main_dict
. I am wondering what are my options in order to have this happens.
second_dic[1]=1000
print(second_dic)
{1: 1000, 2: 2, 3: 7, 4: 7}
print(main_obj.main_dict)
{1: 1, 2: 2, 3: 7, 4: 7}
CodePudding user response:
In your above code, the changes you make to second_dic
won't be reflected in main_dict
because why would they? Those two are two completely different dictionary objects.
If you want aliasing (though it's really not recommended anyway because it leads to hard-to-detect bugs) you have to assign the reference (kinda like the C pointers):
second_dic = main_obj.main_dict # Now second_dic is a pointer to main_dict, in a way
second_dic[1] = 1000
print(main_obj.main_dict)
{1: 1000, ...}
CodePudding user response:
The address of second_dic
and main_dict
are different. So the changes made to second_dic
will not reflect to main_dict
. I used the same above code and displayed the address of them and as expected they are different.
>>> id(second_dic) # To print the address
1911354287192
>>> id(main_obj.main_dict) # To print the address
1911354286952
If you require the second_dic
to point to the main_dict
. we can do it as below.
>>> main_obj.main_dict
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic = main_obj.main_dict # pointing to the same location
>>> second_dic
{1: 6, 2: 10, 3: 10, 4: 3}
>>> second_dic[1] = 111 #Changes the value
>>> second_dic
{1: 111, 2: 10, 3: 10, 4: 3}
>>> main_obj.main_dict # Value gets reflected.
{1: 111, 2: 10, 3: 10, 4: 3}