Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create dynamic variables in python from dictionary keys in for loop

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?

like image 692
Jagrut Trivedi Avatar asked Nov 03 '25 15:11

Jagrut Trivedi


1 Answers

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]
>>>
like image 182
gsinha Avatar answered Nov 06 '25 05:11

gsinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!