I have this program
dict1={
'x':1,
'y':[10,20]
}
for each in list(dict1.keys()):
exec(each=dict1["each"])
#exec('x=dict["x"]')
#exec('y=dict["y"]')
print(x)
print(y)
what i really want is this
exec('x=dict1["x"]') ##commented part
exec('y=dict1["y"]') ##commented part
whatever i am doing in commented part that i want to do in for loop.so, that expected output should be
1
[10,20]
but it is giving error. wanted to create dictionay keys as a variables and values as a varialbe values. but no lock. can anyone please suggest me how to achieve that or it is not possible?
You could use globals () or locals (), instead of exec, depending on scope of usage of those variables.
Example using globals ()
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>>
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>>
>>> dict1={
... 'x':1,
... 'y':[10,20]
... }
>>> dict1
{'y': [10, 20], 'x': 1}
>>> for k in dict1:
... globals()[k] = dict1[k]
...
>>> x
1
>>> y
[10, 20]
>>>
Example using locals ()
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> dict1={
... 'x':1,
... 'y':[10,20]
... }
>>> dict1
{'y': [10, 20], 'x': 1}
>>> for k in dict1:
... locals()[k] = dict1[k]
...
>>> x
1
>>> y
[10, 20]
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With