Last modified: Jan 27, 2026 By Alexander Williams
Convert String to Dictionary in Python
Converting a string to a dictionary is a common Python task. You often get data as a string. It might come from a file, an API, or user input. You need to turn it into a Python dictionary to work with it. This guide shows you the best methods.
Why Convert a String to a Dictionary?
Dictionaries store data as key-value pairs. They are very efficient for lookups. Strings are just sequences of characters. To access structured data inside a string, you must parse it. Converting it to a dict makes the data usable.
Common sources include JSON APIs, configuration files, and data serialization. Knowing how to parse these strings is a key Python skill.
Method 1: Using json.loads() for JSON Strings
The json.loads() function is the standard tool. It converts a JSON-formatted string into a Python dictionary. JSON is a very common data exchange format.
Make sure your string is valid JSON. Keys must be in double quotes. Use this for data from web APIs or JSON files.
import json
# Example JSON string
json_string = '{"name": "Alice", "age": 30, "city": "New York"}'
# Convert string to dictionary
data_dict = json.loads(json_string)
print(data_dict)
print(type(data_dict))
{'name': 'Alice', 'age': 30, 'city': 'New York'}
<class 'dict'>
The string is now a dictionary. You can access values with keys like data_dict['name']. For more on handling dictionary keys, see our Python Dictionary Keys guide.
Method 2: Using ast.literal_eval() for Safe Evaluation
The ast.literal_eval() function is safer than eval(). It evaluates a string containing a Python literal. It works with strings, numbers, tuples, lists, dicts, and booleans.
Use this for strings that look like Python dictionary literals. It is secure for untrusted input because it won't execute code.
import ast
# String that looks like a Python dict literal
py_string = "{'language': 'Python', 'version': 3.11, 'is_cool': True}"
# Safely evaluate to a dictionary
config_dict = ast.literal_eval(py_string)
print(config_dict['version'])
print(config_dict['is_cool'])
3.11
True
Notice the keys use single quotes. This is a Python literal, not JSON. ast.literal_eval() handles it perfectly. To learn more about dictionary literals, read our Python Dict Literal Guide.
Method 3: Custom Parsing for Complex Strings
Sometimes data is not in JSON or Python format. You might have a custom string format. In this case, you need to write a parser. You can split the string and build the dictionary step-by-step.
This method gives you full control. It is useful for simple, predictable formats like key=value pairs.
# Custom string format: "key1=value1;key2=value2"
custom_string = "product=Laptop;price=1200;in_stock=True"
# Initialize an empty dictionary
result_dict = {}
# Split the string into pairs
pairs = custom_string.split(';')
for pair in pairs:
# Split each pair into key and value
key, value = pair.split('=')
# Try to convert numeric or boolean values
if value.isdigit():
value = int(value)
elif value.lower() in ('true', 'false'):
value = value.lower() == 'true'
result_dict[key] = value
print(result_dict)
{'product': 'Laptop', 'price': 1200, 'in_stock': True}
This approach is flexible. You can adapt the logic for any string pattern. After creating your dict, you might need to merge it with other dictionaries.
Common Errors and How to Fix Them
You might encounter errors during conversion. Understanding them saves time.
JSONDecodeError
This happens with json.loads() when the string is not valid JSON. Common causes are single quotes, trailing commas, or incorrect data types.
import json
bad_json = "{'name': 'Bob'}" # Uses single quotes
try:
data = json.loads(bad_json)
except json.JSONDecodeError as e:
print(f"Error: {e}")
Fix it by ensuring double quotes for keys. Or use ast.literal_eval() instead.
ValueError with ast.literal_eval
ast.literal_eval() raises ValueError if the string is not a valid Python literal. It also fails if the string contains complex expressions or function calls.
import ast
unsafe_string = "os.system('ls')" # This is code, not a literal
try:
data = ast.literal_eval(unsafe_string)
except ValueError as e:
print(f"Security feature blocked this: {e}")
This is a security feature. Only use it on trusted data that you know is a simple literal.
Handling Nested Structures
Both json.loads() and ast.literal_eval() handle nested dictionaries and lists automatically. Your string must be correctly formatted.
import json
nested_string = '{"user": {"id": 1, "prefs": {"theme": "dark"}}, "tags": ["python", "web"]}'
nested_dict = json.loads(nested_string)
print(nested_dict['user']['prefs']['theme'])
print(nested_dict['tags'][0])
dark
python
Best Practices for String to Dict Conversion
Follow these tips for reliable code.
Know Your Data Source. Use json.loads() for web data. Use ast.literal_eval() for internal Python data. Write a custom parser for unique formats.
Always Use Try-Except. Wrapping your conversion in a try-except block prevents crashes. You can catch json.JSONDecodeError or ValueError.
Validate the Result. After conversion, check if the dictionary is what you expect. You can use our guide to check if a Python dictionary is empty or inspect its keys.
Conclusion
Converting a string to a dictionary in Python is straightforward with the right tool. For JSON strings, use json.loads(). For Python-like literals, use the safe ast.literal_eval(). For unusual formats, write a custom parser.
Remember to handle errors and validate your data. This skill is essential for working with APIs, files, and configuration data. Now you can turn any structured string into a usable Python dictionary.