Automatic Variable Name Generation

Automatic Variable Name Generation

I am not very experienced in python and I need some help. I would like to generate names for some variables automatically, but i don't know how to. Let's say, i have a dict with 20 values and i want to generate 20 names for the 20 values.

I tried this way, but obviously, python can not assign a string to an item

    for i in range(len(dict)):
       name[i] = 'var_{}'.format(i)
       self.name[i] = dict[i]

The result should look like :

   self.var_0 = content of dict[0]
   self.var_1 = content of dict[1]
   .
   .
   .
   self.var_31 = content of dict[31]
2

2 Answers

You can use the built-in setattr function.

setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

for key, value in dict.items():
    setattr(self, f'var_{key}', value)
1

Please try this. I hope this is what you need.

dict_source={1:'A',2:'B',3:'C'}
name=[]
dict_final={}
for i in range(1,4):
    var_name='var_{}'.format(i)
    name.append(var_name)
    dict_final[name[i-1]]=dict_source[i]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.