How to extract variable name and value from string in python

I have a line

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

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

+4
source share
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'}
+6
source

You can split the string by =and evaluate the dictionary using the function ast.literal_eval:

>>> import ast
>>> ast.literal_eval(ata.split('=')[1].strip())
{'id': '12345', 'name': 'John White'}
+2
source

Source: https://habr.com/ru/post/1626948/


All Articles