5

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

1
  • 2
    Although using the exec() function in Python is discouraged, it would be the easiest way to do what you want: exec("var1 = {'id': '12345', 'name': 'John White'}") Commented Feb 2, 2016 at 3:40

2 Answers 2

6

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

2 Comments

Could you elaborate what exec is actually doing here?
exec is the builtin for dynamic execution of code, there's not much to say other than what's already documented.
2

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

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.