-1

Suppose i have string variable named 'ds'.

ds="{'a': 1, 'b':2}"

And i want to store it in another variable named 'do'.

do=some_function(ds)

So that, when i do this,

print(do['a'])

My output should be 1.

So how do i do that using some in build functions or some small code?

Nikhil.Nixel
  • 555
  • 2
  • 11
  • 25

1 Answers1

1
import ast
ds="{'a': 1, 'b':2}"
do=ast.literal_eval(ds)
print(do['a'])

ast — Abstract Syntax Trees

The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Link For doc

https://docs.python.org/2/library/ast.html

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27