4

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?

2
  • Can you explain what you're trying to do a little better? Commented Dec 15, 2016 at 4: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 - stackoverflow.com/questions/2597278/… Commented Dec 15, 2016 at 4:45

2 Answers 2

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]
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.