Open In App

Ways to convert string to dictionary

Last Updated : 21 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To convert a String into a dictionary, the stored string must be in such a way that a key: value pair can be generated from it.
For example, a string like "{'a': 1, 'b': 2, 'c': 3}" or "a:1, b:10" can be converted into a dictionary This article explores various methods to perform this conversion efficiently.

Using eval()

eval() function allows us to evaluate a string as Python code. If the string is formatted as a valid Python dictionary, we can directly convert it into a dictionary using this function.

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

res = eval(s)
print(res)

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • eval() function parses the string 's' as Python code.
  • Since the string is formatted as a dictionary, it is directly converted into a dictionary object.

Let’s explore some more ways and see how we can convert string to dictionary.

Using json module

If the string is in JSON format, we can use the json module to parse it and convert it into a dictionary.

Python
import json

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

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • The json.loads function parses the string s as a JSON object.
  • It converts the JSON object into a Python dictionary.
  • This method is safe and ideal for strings in JSON format.

Using ast.literal_eval function

ast module provides the literal_eval function, which is similar to eval but safer. It only evaluates strings containing literals, such as dictionaries, lists, and numbers.

Python
import ast

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

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • ast.literal_eval() function parses the string 's' as a literal.
  • It converts the string into a dictionary if it is formatted as one.

Using string manipulation

If the string is not formatted as a dictionary, we can manually process it using string operations to convert it into a dictionary.

Python
s = "a:1, b:2, c:3"

res = {x.split(":")[0]: int(x.split(":")[1]) for x in s.split(", ")}
print(res)

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • We split the string into key-value pairs using the comma and space as a separator.
  • Each pair is further split using the colon to extract the key and value.
  • The result is built as a dictionary using a dictionary comprehension.

Next Article

Similar Reads