简体   繁体   中英

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?

What you want is

for each in dict1.keys():
    exec(each + "=dict1['" + each +"']")

Whether or not this is a good thing to want is another question.

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]
>>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM