Hassan Naqvi
Hassan Naqvi

Reputation: 423

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

Upvotes: 5

Views: 3472

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

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'}

Upvotes: 2

wim
wim

Reputation: 362657

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'}

Upvotes: 6

Related Questions