7

I have the following string which is a Python dictionary stringified:

some_string = '{123: False, 456: True, 789: False}'

How do I get the Python dictionary out of the above string?

Thierry Lam
  • 45,304
  • 42
  • 117
  • 144

3 Answers3

12

Use ast.literal_eval:

Safely evaluate an expression node or a string containing a Python expression. 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 expressions from untrusted sources without the need to parse the values oneself.

Example:

>>> some_string = '{123: False, 456: True, 789: False}'
>>> import ast
>>> ast.literal_eval(some_string)
{456: True, 123: False, 789: False}
Community
  • 1
  • 1
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
10

Well, you can do

d = eval(some_string)

But if the string contains user input, it's a bad idea because some random malicious function could be in the expression. See Safety of Python 'eval' For List Deserialization

So a safer alternative might be:

import ast
d = ast.literal_eval(some_string)

From http://docs.python.org/library/ast.html#ast.literal_eval :

The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Community
  • 1
  • 1
Joe Koberg
  • 25,416
  • 6
  • 48
  • 54
3

The only safe way to do it is with ast.literal_eval (it's safe because, differently from built-in eval, """The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.""".

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395