1

I got a string, it's like:

"{'a': 1, 'b': 2, 'c': 3}"

I want to assign a variable to this string and make the variable a dict. It sounds easy, but I spend half hour and didn't figure it out. How to do it?

Zen
  • 4,381
  • 5
  • 29
  • 56

1 Answers1

8

Use the ast.literal_eval() function as follows:

>>> import ast
>>> ast.literal_eval("{'a': 1, 'b': 2, 'c': 3}")
{'a': 1, 'b': 2, 'c': 3}

You could use it in a programme as follows:

import ast
dictString = "{'a': 1, 'b': 2, 'c': 3}";
dictFinal = ast.literal_eval(dictString)
print (dictFinal)

There is more help in the docs at this link

Morgoth
  • 4,935
  • 8
  • 40
  • 66