简体   繁体   中英

Is it possible to assign a variable as a value in a dictionary (for Python)?

for variables 'a' and 'b' in dictionary 'dict1' is it possible to later call variable 'a' using its key given in 'dict1' to assign a value to it??

 a=""
 b=""
 dict1= {0:a,1:b}

    dict1[0] = "Hai"    #assign a value to the variable using the key

    print(a)            #later call the variable``` 

No, when you do the assignment {key:value}, the value doesn't refer to the original variable, so mutating either one will not affect the other.

The variable is not set automatically, what you could do is:

def update_dic(a,b):
   dict1={0:a, 1:b}
   return dict1

def update_vars(dict1):
   return dict1[0],dict1[1]

Every time you call the first function your dictionary is getting updated, and for the second time you always get a and b back.

You could do something similar using a class to store your variables and the indexing dictionary:

class Variables():
    def __init__(self):
        self.varIndex = dict()

    def __getitem__(self,index):
        return self.__dict__[self.varIndex[index]]

    def __setitem__(self,index,value):
        self.__dict__[self.varIndex[index]] = value

variables = Variables()

variables.a = 3
variables.b = 4
variables.varIndex = {0:"a",1:"b"}
variables[0] = 8
print(variables.a) # 8

We can do this by using two dictionaries with the same amount of variables:

This allows to access the variable 'a' using the key '0' and then altering its value using 'dict2' and later get the value by calling 'a'.

however remember that the variables need to written as string ie in quotes, it doesn't work when used as a regular variable.

 dict1= {0:'a',1:'b'}
 dict2={'a':'x','b':'y'}

 dict2[dict1[0]]="Hai"    #assign a value to the variable using the key

 print(dict2['a'])          #later call the variable ````




The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM