Python convert string to dictionary | Example code

Using json.loads() or ast.literal_eval() function can convert string to dictionary in Python. This are inbuilt functions.

Example convert string to dictionary in Python

Simple example code.

Using json.loads()

import json

s = '{"X" : 1, "Y" : 2, "Z" : 3}'

res = json.loads(s)

print(res)
print(type(res))

Output:

Python convert string to dictionary

Using ast.literal_eval()

import ast

s = '{"X" : 1, "Y" : 2, "Z" : 3}'

res = ast.literal_eval(s)

print(res)

Output: {‘X’: 1, ‘Y’: 2, ‘Z’: 3}

How to convert a String representation of a Dictionary to a dictionary?

Answer: Use the built-in ast.literal_eval: import ast module for it.

import ast

str1 = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
res = ast.literal_eval(str1)

print(res)
print(type)

Output:

{‘muffin’: ‘lolz’, ‘foo’: ‘kitty’}

Do comment if you have any doubts and suggestions on this Python convert topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.