Home > database >  call dictionary variable names in for-loops
call dictionary variable names in for-loops

Time:01-10

i want to generate multiple objects with the same name but numbered using a for loop. I was able to generate the Objects using a dictionary, but no I don't know how to call it to assign the values to the object.

class Class:
    def __init__(self):
        self.value = None

dic = {}
for i in range(9):
    dic['object{0}'.format(i)] = Object()

now it generates objects called object0, object1, ... . But now I want to assign the attribute value to every object, so object0.value = 0, object1.value = 1, ... . How can I call the objects in every loop by their current name?

CodePudding user response:

By using the key values:

dic = {}

for i in range(9):
     dic['object{0}'.format(i)] = Object()
     dic['object{0}'.format(i)].value="your value"

Or in a 2nd loop:

dic = {}

for i in range(9):
     dic['object{0}'.format(i)] = Object()

for i in range(9):
     dic['object{0}'.format(i)].value="your value"
  •  Tags:  
  • Related