3

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?

Jagrut Trivedi
  • 1,271
  • 14
  • 18
  • Can you explain what you're trying to do a little better? – Jacob G. Dec 15 '16 at 04:34
  • 1
    You're wanting to populate global namespace with variables from a dictionary, with variable names defined by the dictionary keys? Sounds bad. See this question for possible alternatives - http://stackoverflow.com/questions/2597278/python-load-variables-in-a-dict-into-namespace – Andrew Guy Dec 15 '16 at 04:45

2 Answers2

4

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.

John Coleman
  • 51,337
  • 7
  • 54
  • 119
4

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]
>>>
gsinha
  • 1,165
  • 2
  • 18
  • 43
  • This one is definitely preferred as it avoids `exec`. Re-casting the answer in the locals case (safest): `for k, v in dict1.items(): locals()[k] = v` – Zephaniah Grunschlag Mar 08 '21 at 05:59