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 Answers
You can use the built-in setattr function.
setattr(x, 'foobar', 123)is equivalent tox.foobar = 123.
for key, value in dict.items():
setattr(self, f'var_{key}', value)
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]