Is it possible to write a reference to an object in the dictionary value in Python?

Viewed 23

Can I use a value in a dictionary as a reference to an object? Example:

a = 60
b = 70
dict_a = {'command_1':a,'command_2':b}
print(dict_a)
##{'command_1': 60, 'command_2': 70}

When we change "a" was the next change in the dictionary

b = 50
print(dict_a)
##{'command_1': 60, 'command_2': 50}
1 Answers

Yes, you can, but not this way.

What happens here, is this:

b = 70 
# b is now reference to anonymous int object with value of 70

dict_a = {'command_1':a,'command_2':b} 
# dict_a['command_2'] now points *to the same int object* as b

b = 50
#b now points to another anonymous int object with value of 50

Bottom line. When doing

b=X
something=b

we are pointing both b and something to X. When we later change b to point to Y, something still points to X. when assigning, look at right side of previous assignment.

One of the things you can do is use some smarter object as dict value, whose internal value can be changed by calling some method in it.

eg. assuming a myint class which extends int:

n=myint(5)
mydict=dict(command_1=n)
n.set_value(8)

This should work as n still references the same object as the one in dict.

I don't have python docs at hand, perhaps you can do this with int object as well, but I doubt it, as int objects are immutable.

Related