The problem:
I have a dictionary of keys and values:
param_dict = {
'VAR1' : 'abcd',
'VAR2' : (1, 1),
'VAR3' : 10.0
}
I want to write a function that takes in such a dictionary, and will set each key-value pair as a global variable.
What I have so far:
I have already figured out how to create global variables from my dictionary (as described in a number of answers to this older question). I run into problems only when trying to write my code (shown in the cell below) as a function.
# Set defined values as global variables
for k, v in param_dict.items():
exec(k + '=v')
You can see that each dictionary key is now the name of a global variable, and each dictionary value is the corresponding value:
print(VAR1) # Prints the value of the global variable VAR1
But I don't know how to accomplish the same thing with a function, since placing all my code within a function will result in the creation of local variables, not global variables.
def make_globals(param_dict):
# Set defined values as global variables
for k, v in param_dict.items():
exec(k + '=v')
make_globals(param_dict=param_dict)
print(VAR1) # Returns a NameError
I know you can set global variables from within a function using global
(as shown here and here), but this method requires the name of the variable to be hard-coded into the function itself (at least as far as I can tell). This doesn't work for me since my global variable names can vary and I'm looping through multiple key-value pairs that I want to use as global variables. Is there a way around this?