To convert a string representation of a dictionary into a Python dictionary, you can use the following methods, depending on the string’s format and safety requirements:
1. Using ast.literal_eval() (Recommended for Python-Style Strings)
Use Case: Safely evaluate strings containing Python literals (e.g., None, True, single quotes).
Example:
import ast
# String with Python-style syntax (single quotes, None, booleans)
s = "{'name': 'Alice', 'age': 30, 'is_student': False, 'pet': None}"
# Convert to a dictionary
d = ast.literal_eval(s)
print(d)
# Output: {'name': 'Alice', 'age': 30, 'is_student': False, 'pet': None}
Features:
- Handles Python-specific syntax (e.g.,
None,True/False). - Safe: Only parses literals, not arbitrary code.
2. Using json.loads() (For JSON-Compliant Strings)
Use Case: Strings formatted as JSON (double quotes, true/false/null).
Example:
import json
# JSON-style string (double quotes, lowercase booleans, null)
s = '{"name": "Alice", "age": 30, "is_student": false, "pet": null}'
# Convert to a dictionary
d = json.loads(s)
print(d)
# Output: {'name': 'Alice', 'age': 30, 'is_student': False, 'pet': None}
Notes:
- JSON requires double quotes (
") and lowercasetrue/false/null. - Converts JSON
nullto PythonNone.
3. Using eval() (Unsafe, Not Recommended)
Use Case: Only use if you fully trust the input string (security risk).
Example:
s = "{'name': 'Alice', 'age': 30, 'is_student': False}"
# Convert to a dictionary (UNSAFE!)
d = eval(s)
print(d)
# Output: {'name': 'Alice', 'age': 30, 'is_student': False}
Warnings:
- Security Risk: Executes arbitrary code (e.g.,
s = "__import__('os').system('rm -rf /')"would delete files!). - Avoid unless the input is fully controlled.
Key Differences
| Method | Syntax Support | Safety | Use Case |
|---|---|---|---|
ast.literal_eval() | Python literals (None, True, etc.) | Safe | General-purpose (recommended) |
json.loads() | JSON format (null, true, false) | Safe | JSON data from APIs/files |
eval() | Any Python code (including functions) | Unsafe | Avoid unless input is fully trusted |
Handling Edge Cases
1. Single vs. Double Quotes
Convert single quotes to double quotes for JSON compatibility:
s = "{'name': 'Alice'}"
s_fixed = s.replace("'", '"') # Convert to {"name": "Alice"}
d = json.loads(s_fixed)
2. JSON true/false/null to Python True/False/None
json.loads() automatically converts:
true→Truefalse→Falsenull→None
3. Malformed Strings
Handle errors gracefully:
s = "{'name': 'Alice', age: 30}" # Missing quotes around 'age'
try:
d = ast.literal_eval(s)
except SyntaxError:
print("Invalid string format!")
Full Workflow Example
import ast
def string_to_dict(s):
try:
return ast.literal_eval(s)
except (SyntaxError, ValueError):
print("Error: Invalid dictionary format")
return {}
# Test with valid and invalid strings
valid_s = "{'name': 'Alice', 'age': 30}"
invalid_s = "{'name': 'Alice', age: 30}" # Missing quotes
print(string_to_dict(valid_s)) # {'name': 'Alice', 'age': 30}
print(string_to_dict(invalid_s)) # Error: Invalid dictionary format → {}
Summary
- Use
ast.literal_eval()for Python-style strings (safest and most flexible). - Use
json.loads()for JSON-formatted strings. - Avoid
eval()due to security risks.