how to make child of a list become a variable in python
-
28-10-2019 - |
Question
i'm trying to make a web only using couchdb and couchapp...
but for some reason i need external process using python..
and now i'm stuck how to handle post variable in python...
i'v read this(and it works) and this...
but i want it like this :
>>> a = {"success":1,"data":{"var1":1,"var2":2,"var3":3}}
>>> a["data"]["var2"]
2
>>> var2
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
var2
NameError: name 'var2' is not defined
>>> for key, value in a["data"].items():
print (key, value)
('var1', 1)
('var3', 3)
('var2', 2)
>>> var1
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
var1
NameError: name 'var1' is not defined
>>>
i want, when i type var2, it return 2
in other word how to make nested child object become a variable when i don't know how much len
the data.. it's because in external python, how to handle post variable is like this req["form"]["var1"]
Solution
you should try to update your local (not recommended) or global dictionnary with your data dictionnary
>>> a = {"success":1,"data":{"var1":1,"var2":2,"var3":3}}
>>> a["data"]["var2"]
2
>>> locals().update(a["data"])
>>> var2
2
or
>>> globals().update(a["data"])
>>> var2
2
To do this in a safe way, you have to trust the source of the data you're updating your globals dictionnary with, to avoid builtin's replacement or other funny code injections.
OTHER TIPS
Could use the python "exec" statement to build a string and then execute it dynamically.
a = {"success":1,"data":{"var1":1,"var2":2,"var3":3}}
for key, value in a["data"].items():
exec('%s=%s' % (key, value, ))
print 'var1:', var1
print 'var2:', var2
print 'var3:', var3
To do this safely, I would suggest something like:
allowed_variables = ('var1', 'var2', 'var3')
for k,v in a["data"].iteritems():
if k in allowed_variables:
locals.update({k:v})