Skip to content

Python convert string to dictionary | Example code

  • by

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

Example convert string to the 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 or suggestions on this Python convert topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading