Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract variable name and value from string in python

I have a string

data = "var1 = {'id': '12345', 'name': 'John White'}"

Is there any way in python to extract var1 as a python variable. More specifically I am interested in the dictionary variables so that I can get value of vars: id and name.python

like image 500
Hassan Naqvi Avatar asked Feb 02 '16 03:02

Hassan Naqvi


People also ask

How do you get the value of a variable given its name in a string?

Assuming that you know the string is safe to evaluate, then eval will give the value of the variable in the current context. Do not ever use eval (or exec ) on data that could possibly come from outside the program in any form. It is a critical security risk.

How do you extract a value from a variable in Python?

You need to split the string and not strip the string. split returns a list and strip() returns a string with the required substring removed from either side of the string. . split will split the string into a list based on the delimiter and .

How do you find the variable value of a string in Python?

Python – Variables in String All we need to do is enclose the variables with curly braces {variable} and place this variable inside the string value, wherever required. An example is given below. In the above program, we have a variable named var1 and we inserted this variable in the string using formatted strings.

What is the value of __ name __?

In the top-level code environment, the value of __name__ is "__main__" . In an imported module, the value of __name__ is the module's name as a string.


2 Answers

This is the functionality provided by exec

>>> my_scope = {}
>>> data = "var1 = {'id': '12345', 'name': 'John White'}"
>>> exec(data, my_scope)
>>> my_scope['var1']
{'id': '12345', 'name': 'John White'}
like image 144
wim Avatar answered Sep 19 '22 18:09

wim


You can split the string with = and evaluated the dictionary using ast.literal_eval function:

>>> import ast
>>> ast.literal_eval(ata.split('=')[1].strip())
{'id': '12345', 'name': 'John White'}
like image 44
Mazdak Avatar answered Sep 18 '22 18:09

Mazdak