Reputation: 60
x = 2
dict_1 = {'One': x}
def my_fun():
global x
x = 1
my_fun()
print('x is: ', x, '| dict_1 is :', dict_1)
Output is :
x is: 1 | dict_1 is : {'One': 2}
How can I reflect the change in a variable in dictionary value?
Upvotes: 0
Views: 778
Reputation: 2139
I think most people would do something like this. The keyword 'global' is very rarely appropriate.
x = 2
dict_1 = {'One': x}
def my_fun(dictionary):
dictionary['One'] = 1
return dictionary
dict_1 = my_fun(dict_1)
x = dict_1['One']
print('x is: ', x, '| dict_1 is :', dict_1)
You want data sources to be authoritative. So there should be one data structure that holds the value and then code goes to that data structure for values. You can put them in variables or other data structures for convenience.
Upvotes: 0
Reputation: 966
I'm not sure what the constraints are in your question, or what exactly you're trying to achieve, but one way to solve the problem is to adjust your code so it looks like this:
global x, dict_1
x = 2
dict_1 = {'One': x}
def my_fun():
dict_1['One'] = x
x = 1
my_fun()
print('x is: ', x, '| dict_1 is :', dict_1)
Upvotes: 0
Reputation: 155684
Do dict_1['One'] = x = 1
so you reassign both? There's no magic way to make this happen; once dict_1
is constructed, it has no further relationship to the name x
, and the object x
refers to (an int
) is immutable, so you can't do anything to take advantage of x
and dict_1['One']
being aliases to the same object (initially).
There are all sorts of terrible solutions to do something like this (making the value of dict_1
a lambda
that returns x
, making dict_1
a function that constructs the dict
with the current x
, using module level __getattr__
instead of defining dict_1
such that loading dict_1
gets a freshly constructed dict
, etc.), but all of them require some additional steps that would make print('x is: ', x, '| dict_1 is :', dict_1)
not work as written, or make dict_1
not persistent, or both.
Upvotes: 2