In Python, a common requirement is to convert string content into a dictionary. For example, consider the string "{'a': 1, 'b': 2, 'c': 3}". The task is to convert this string into a dictionary like {'a': 1, 'b': 2, 'c': 3}. This article demonstrates several ways to achieve this in Python.
Using ast.literal_eval
This method is one of the most efficient and safe ways to convert a string representation of a dictionary into an actual dictionary.
import ast
# Input string
s = "{'a': 1, 'b': 2, 'c': 3}"
# Convert string to dictionary using ast.literal_eval
result = ast.literal_eval(s)
print(result)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- ast.literal_eval function safely evaluates the string as a Python literal.
- This method is preferred because it avoids the risks associated with using eval().
Using json.loads
If the string uses double quotes instead of single quotes, you can use the json.loads method from the json module.
import json
# Input string
s = '{"a": 1, "b": 2, "c": 3}'
# Convert string to dictionary using json.loads
res = json.loads(s)
print(res)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- json.loads function parses the string as a JSON object and converts it to a Python dictionary.
- Ensure the input string follows JSON formatting (e.g., double quotes for keys and values).
Using eval()
eval() function can also be used for this purpose but should be avoided in production code due to potential security risks.
# Input string
s = "{'a': 1, 'b': 2, 'c': 3}"
# Convert string to dictionary using eval
res = eval(s)
print(res)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- eval() function evaluates the string as a Python expression.
- While this method works, it can execute arbitrary code, making it unsafe for untrusted input.
Using String Manipulation and split
For simple strings with a fixed pattern, you can manually parse the string.
# Input string
s = "{'a': 1, 'b': 2, 'c': 3}"
# Remove curly braces and split the string
pairs = s.strip('{}').split(', ')
res = {pair.split(': ')[0].strip("'"): int(pair.split(': ')[1]) for pair in pairs}
print(res)
Output
{'a': 1, 'b': 2, 'c': 3}
Explanation:
- The string is stripped of curly braces using strip('{}').
- The string is split into key-value pairs using split(', ').
- Dictionary comprehension is used to create the dictionary by splitting and processing each pair.