Reputation: 165
How can I link a variable to a dictionary value in Python? Consider the following code:
a_var = 10
a_dict = {'varfield':a_var, 'first':25, 'second':57}
# a_dict['varfield'] == 10 now
a_var = 700
# a_dict['varfield'] == 10 anyway
So is there a way to link the value of a variable to a field in a dictictionary without looking up for that field an updating it's value manually?
Upvotes: 2
Views: 121
Reputation: 27575
w = [410]
myDict = {'myvar': w}
print myDict
#{'myvar': [410]}
w[0] = 520
print myDict
#{'myvar': [520]}
That's the version of the code of M4rtini with a list instead of an instance of a class.
He is obliged to modify v1
(in fact its attribute value
) with the instruction v1.value = ...
,
I am obliged to modify the value in the list with w[0] = ...
The reason to act like this is that what you erroneously called a variable, and that is in fact an identifier, doesn't designates a variable in the sense of a "chunk of memory whose content can change" but references an object to which the identifier is binded, object whose value cannot change because it is an immutable object.
Please read the explanations of the documentation on the data model and the execution model of Python which is quite different from the ones of languages such as Java, PHP, etc.
Upvotes: 1
Reputation: 13539
You would need to set the value of the dictionary key, to an object that you can change the value of.
For example like this:
class valueContainer(object):
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value.__repr__()
v1 = valueContainer(1)
myDict = {'myvar': v1}
print myDict
#{'myvar': 1}
v1.value = 2
print myDict
#{'myvar': 2}
Upvotes: 1