Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you convert a stringed dictionary to a Python dictionary? [duplicate]

Tags:

python

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?

like image 432
Thierry Lam Avatar asked May 07 '26 15:05

Thierry Lam


1 Answers

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}
like image 104
Mark Byers Avatar answered May 10 '26 05:05

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!