Is there a Pythonic way to assign the values of a dictionary to its keys, in order to convert the dictionary entries into variables? I tried this out:
>>> d = {'a':1, 'b':2}
>>> for key,val in d.items():
exec('exec(key)=val')
exec(key)=val
^
SyntaxError: invalid syntax
I am certain that the key-value pairs are correct because they were previously defined as variables by me before. I then stored these variables in a dictionary (as key-value pairs) and would like to reuse them in a different function. I could just define them all over again in the new function, but because I may have a dictionary with about 20 entries, I thought there may be a more efficient way of doing this.
This was what I was looking for:
d = {'a':1, 'b':2}
for key,val in d.items():
exec(key + '=val')
NOTE: As noted by @divenex in the comments, this solution only creates global variables -- it will not create local variables in a function.
Move the code inside a function and you will get an error.
def func():
d = {'a':1, 'b':2}
for key,val in d.items():
exec(key + '=val')
print(a,b)
func()
Error message:
NameError: name 'a' is not defined