I’m writing a program that pulls a list of departments from a database. I want to avoid hardcoding this since the list may change.
I want to create a variable for each department to populate questions into a GUI. The problem I have is that I can create variables from the database list using the vars() function. I’m then storing the list of variable names so I can reference them elsewhere in my program. As long as I do everything in the same def, there is no problem. But I don’t know how to reference the dynamically created variables in a separate function.
Since I won’t know the variable names ahead of time, I don’t know how to make them available in other functions.
deptList = ['deptartment 1', 'deptartment 2', 'deptartment 3', 'deptartment 4', 'deptartment4']
varList=[]
def createVariables():
global varList
for i in range(len(deptList)):
templst=deptList[i].replace(' ', '')
varList.append(templst+'Questions')
globals()['{}'.format(varList[i])] = []
def addInfo():
global varList
print('varlist',vars()[varList[1]]) #Keyerror
createVariables()
print(varList)
vars()[varList[1]].append('This is the new question')
print('varlist',vars()[varList[1]]) #Prints successfully
addInfo()