Open In App

Convert String Dictionary to Dictionary in Python

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The goal here is to convert a string that represents a dictionary into an actual Python dictionary object. For example, you might have a string like “{‘a’: 1, ‘b’: 2}” and want to convert it into the Python dictionary {‘a’: 1, ‘b’: 2}. Let’s understand the different methods to do this efficiently.

Using ast.literal_eval

ast.literal_eval function from the ast module is the safest and most efficient way to convert a string dictionary into a dictionary.

Python
import ast

a = "{'a': 1, 'b': 2}"
res = ast.literal_eval(a)
print(type(res),res)

Output
<class 'dict'> {'a': 1, 'b': 2}

Explanation: ast.literal_eval(a) safely evaluates the string a and returns a Python dictionary.

Using json.loads

json.loads() converts a JSON-formatted string into a Python dictionary. However, JSON strings must use double quotes (“) for both keys and string values. Using single quotes (‘) will raise a JSONDecodeError, as the json module strictly follows the official JSON standard.

Python
import json

a = '{"a": 1, "b": 2}'
res = json.loads(a)
print(type(res),res)

Output
<class 'dict'> {'a': 1, 'b': 2}

Explanation: json.loads(a) parses the string a as JSON and returns the corresponding Python dictionary.

Using eval

eval function can also be used to convert a string dictionary into a dictionary. However, it is not recommended for untrusted input due to security risks.

Python
a = "{'a': 1, 'b': 2}"
res = eval(a)
print(type(res),res)

Output
<class 'dict'> {'a': 1, 'b': 2}

Explanation: eval(a) evaluates the string a as a Python expression, which converts it into an actual dictionary.

Using String Manipulation and dict()

If the input string is simple and predictable, we can manually parse it using string manipulation techniques and dict() function.

Python
a = "{'a': 1, 'b': 2}"

a = a.strip("{}")
res = dict(item.split(": ") for item in a.split(", "))
print(type(res),res)

Output
<class 'dict'> {"'a'": '1', "'b'": '2'}

Explanation:

  • a.strip(“{}”) removes the curly braces from the string.
  • a.split(“, “) splits the string into individual key-value pairs.
  • item.split(“: “) splits each key-value pair into key and value.
  • dict() converts the list of key-value pairs into a dictionary.


Practice Tags :

Similar Reads