I am trying to iterate over a dictionary to create new lists on a function. I get NameError when calling one of the variables at the end to create a dataframe.
def multiply(number):
list1 = []
list2 = []
appendDict = {
'list1': '1',
'list2': '2'}
for i in range(10):
for k, v in appendDict.items():
eval(k).append(i*number*int(v))
eval(k).append(i*number*int(v))
df = {k:eval(k) for k, v in appendDict.items()}
df = pd.DataFrame(df)
return df
print(multiply(1))
When I try running the code in the very same file, I get a NameError, stating that the list1 variable is not defined.
"NameError: name 'list1' is not defined"
I understand that it is not defined OUTSIDE of the function, but if it is already defined IN the function and only used IN the function, why do I need to define it as global? When defining the variable as global, the problem disappears but I want to understand why.
As a side note, if I run this small loop within the function, it prints out the contents of the variables seamlessly, without them having to be defined as global variables. The problem comes when trying to build a dictionary out of the variables.
for k, v in appendDict.items():
print(eval(k))
UPDATE: Solved by creating a scope variable and inserting it in the eval function.
scope=locals()
df = {k:eval(k, scope) for k, v in appendDict.items()}
This was a duplicate question: eval fails in list comprehension Python: How can I run eval() in the local scope of a function