How to convert a string to a dictionary in Python
Discover multiple ways to convert a string to a dictionary in Python. Get tips, see real-world examples, and learn to debug common errors.

You often need to convert a string to a dictionary in Python, especially when you handle data from APIs or files. Python offers several built-in methods to manage this conversion efficiently.
In this article, you'll learn key techniques that use json.loads() and ast.literal_eval(). We'll also cover real-world applications, practical tips, and common debugging advice to master this skill.
Using json.loads() for JSON strings
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
my_dict = json.loads(json_string)
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'city': 'New York'}
The json.loads() function is your go-to method for converting a JSON-formatted string into a Python dictionary. It’s the standard for handling data from web APIs and configuration files because JSON is a universal data exchange format. The function parses the string, directly translating JSON objects into their Python dictionary equivalents.
For the conversion to succeed, the string must be valid JSON. This is a crucial detail. It means keys and string values must be enclosed in double quotes ("), not single quotes. Using json.loads() is both fast and secure, as it’s built specifically to safely process the well-defined structure of JSON data.
Common string to dictionary conversion methods
While json.loads() is ideal for JSON, other methods are better suited for strings that look like native Python dictionaries but aren't in strict JSON format.
Using ast.literal_eval() for Python dictionary strings
import ast
dict_string = "{'name': 'John', 'age': 30, 'city': 'New York'}"
my_dict = ast.literal_eval(dict_string)
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'city': 'New York'}
When your string looks like a Python dictionary but uses single quotes, ast.literal_eval() is the perfect tool. It safely parses strings containing Python literals—like dictionaries, lists, or numbers—and converts them into the corresponding Python object. This makes it more flexible than json.loads() for non-JSON formatted strings.
- It correctly interprets Python syntax, such as single-quoted keys, that would cause an error with
json.loads(). - It's a secure alternative to
eval(), as it only processes literal structures and blocks any complex expressions or code execution.
Using the eval() function with caution
dict_string = "{'name': 'John', 'age': 30, 'city': 'New York'}"
my_dict = eval(dict_string)
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'city': 'New York'}
The eval() function is a powerful but risky tool. It can parse and execute any Python expression from a string, which makes it seem convenient for converting dictionary-like strings. However, this power is also its greatest weakness.
- Using
eval()on untrusted input, like data from an external source, opens a major security vulnerability. - A malicious string could execute arbitrary code on your system.
For this reason, it’s almost always better to use ast.literal_eval(). It provides the same flexibility for Python literals without the dangerous side effects.
Converting key-value strings with dictionary comprehension
kv_string = "name=John,age=30,city=New York"
my_dict = {k: v for k, v in (pair.split('=', 1) for pair in kv_string.split(','))}
print(my_dict)--OUTPUT--{'name': 'John', 'age': '30', 'city': 'New York'}
When you have a custom-formatted string of key-value pairs, dictionary comprehension offers a powerful, built-in way to parse it. It’s a concise method that’s especially useful for formats like URL query parameters.
- The process starts by splitting the main string at each comma (
,) to isolate the pairs. - Then, each pair is split at the equals sign (
=) to separate the key from its value. - The comprehension assembles these pieces into a dictionary. Notice that all resulting values are strings.
Advanced string to dictionary techniques
Beyond the basics, you'll sometimes face more complex strings that require advanced parsing techniques for custom formats, configuration files, or nested data structures—challenges that AI coding with Python can help solve efficiently.
Parsing with regular expressions
import re
complex_string = "{name: 'John Doe', age: 30, city: 'New York'}"
pattern = r'(\w+):\s*[\'\"]?([^\'\",}]+)[\'\"]?'
my_dict = dict(re.findall(pattern, complex_string))
print(my_dict)--OUTPUT--{'name': 'John Doe', 'age': '30', 'city': 'New York'}
Regular expressions are your best bet for strings with inconsistent or custom formatting that other methods can't handle. This approach is powerful when you need to parse data that doesn't conform to strict JSON or Python literal syntax, like having unquoted keys, which requires mastery of using regular expressions.
- The
re.findall()function scans the string, using a custom pattern to locate and extract all key-value pairs. - It returns a list of tuples, such as
[('name', 'John Doe'), ('age', '30')]. - The
dict()constructor then efficiently converts this list of pairs into your final dictionary.
Converting configuration strings to dictionaries
config = """
DB_HOST = localhost
DB_PORT = 5432
DB_USER = admin
"""
lines = [line.strip().split(' = ') for line in config.strip().split('\n')]
config_dict = dict(lines)
print(config_dict)--OUTPUT--{'DB_HOST': 'localhost', 'DB_PORT': '5432', 'DB_USER': 'admin'}
This technique is ideal for parsing simple configuration data, like environment variables stored in a multiline string. It uses a list comprehension to quickly transform the text into a dictionary, which is a common task when loading settings that often comes from reading configuration files.
- The string is first broken into individual lines using
split('\n'). - For each line,
strip()removes whitespace, andsplit(' = ')separates the key from the value. - Finally, the
dict()constructor efficiently converts this list of key-value pairs into a dictionary.
Working with nested dictionary strings
import json
nested_json = '{"user": {"name": "John", "profile": {"age": 30, "city": "New York"}}}'
data = json.loads(nested_json)
print(f"User: {data['user']['name']}, City: {data['user']['profile']['city']}")--OUTPUT--User: John, City: New York
When your string contains dictionaries inside other dictionaries, json.loads() handles the complexity for you. It recursively parses the entire string, correctly converting nested JSON objects into nested Python dictionaries. This is a common scenario when working with complex API responses, where understanding accessing dictionary keys becomes essential.
- To access the inner data, you simply chain the keys using square brackets, like
data['user']['profile']['city'], to navigate through the structure.
Move faster with Replit
Replit is an AI-powered development platform where all Python dependencies come pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques to building complete applications with Agent 4, a tool that takes your description and handles the code, databases, APIs, and deployment.
Instead of piecing together functions, you can describe the app you want to build and let the Agent take it from idea to working product:
- An API data visualizer that parses JSON responses from a web service and displays the key information in a clean dashboard.
- A configuration file loader that reads key-value strings and converts them into a settings dictionary for an application.
- A log parser utility that uses regular expressions to extract structured data from messy log files and turns it into a dictionary for analysis.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with the right tools, you can run into issues like malformed strings or unexpected data types during conversion.
A common mistake is feeding json.loads() a string with single quotes, which triggers a JSONDecodeError because the JSON standard requires double quotes. An easy fix is to preprocess the string using my_string.replace('`'`, '"') to swap the quotes before parsing. This simple step ensures your string is correctly formatted for the function.
Another challenge is that numbers can end up as strings in your final dictionary, like '30' instead of 30. This often happens when you parse custom formats with dictionary comprehensions or regular expressions. To fix this, you'll need to post-process the dictionary by iterating through its values and using int() or float() to convert the numeric strings into their proper data types.
When working with nested dictionaries, you risk a KeyError if you try to access a key that doesn't exist, which can crash your program. Instead of direct access like data['user']['profile'], use the .get() method. Writing data.get('user', {}).get('profile') is much safer—it returns None if a key is missing, allowing your code to handle incomplete data gracefully without failing.
Fixing malformed JSON with mismatched quotes in json.loads()
A common pitfall with json.loads() is feeding it a string that uses single quotes instead of the required double quotes. This mistake immediately triggers a JSONDecodeError because it violates the strict JSON standard. The code below shows this error in action.
import json
# Invalid JSON: single quotes instead of double quotes
invalid_json = "{'name': 'John', 'age': 30}"
data = json.loads(invalid_json)
print(data)
This code fails because json.loads() is called on a string that isn't valid JSON. The single quotes in invalid_json violate the standard, causing the parser to stop and raise an error. See the next example for a fix.
import json
# Invalid JSON: single quotes instead of double quotes
invalid_json = "{'name': 'John', 'age': 30}"
valid_json = invalid_json.replace("'", '"')
data = json.loads(valid_json)
print(data)
The fix is simple: use the replace("'", '"') method on your string before parsing. This one-liner swaps all single quotes for the double quotes that json.loads() expects, making the string valid JSON. It's a quick way to handle data that's almost, but not quite, in the right format. This often happens when you get data from sources that generate Python-like string representations instead of strict JSON.
Converting string values to numbers after using json.loads()
Converting string values to numbers after using json.loads()
Sometimes, even with valid JSON, numbers are represented as strings, like "123" instead of 123. When json.loads() parses this, it keeps them as strings, which can lead to a TypeError if you try to perform math operations.
The code below demonstrates what happens when you attempt arithmetic with a string value that should be a number.
import json
json_string = '{"id": "123", "score": "97.5"}'
data = json.loads(json_string)
# Attempting arithmetic on string values
new_score = data["score"] + 2.5
print(f"New score: {new_score}")
This operation triggers a TypeError because Python can't add a number to a string. The value of data["score"] must be converted first. The code below demonstrates how to do this.
import json
json_string = '{"id": "123", "score": "97.5"}'
data = json.loads(json_string)
# Convert strings to appropriate numeric types before arithmetic
new_score = float(data["score"]) + 2.5
print(f"New score: {new_score}")
To fix the TypeError, you must convert the string to a number before doing math. The solution uses float(data["score"]) to transform the string value into a floating-point number, allowing the calculation to proceed. You'll often encounter this when APIs send numbers as strings inside JSON. It’s a good practice to always verify and convert data types after parsing to ensure your code runs smoothly without type-related errors.
Safely accessing nested keys after parsing JSON with json.loads()
When you parse nested JSON, directly accessing keys with square brackets is risky. If a key is missing from the data—a common issue with API responses that have optional fields—your code will crash with a KeyError. The following code demonstrates this exact scenario.
import json
user_data = '{"user": {"name": "John", "profile": {"age": 30}}}'
data = json.loads(user_data)
# This will raise a KeyError
city = data["user"]["profile"]["city"]
print(f"User city: {city}")
The code attempts to access the city key, which is missing from the nested profile dictionary. This direct lookup triggers a KeyError because it can't handle optional fields. The following code shows a more robust approach.
import json
user_data = '{"user": {"name": "John", "profile": {"age": 30}}}'
data = json.loads(user_data)
# Safe access with get() method and a default value
city = data["user"]["profile"].get("city", "Unknown")
print(f"User city: {city}")
The fix is to use the .get() method, which provides a safe way to access keys that might not exist. By calling data["user"]["profile"].get("city", "Unknown"), the code attempts to retrieve the city. If it's missing, it returns the default value "Unknown" instead of raising a KeyError. This approach is essential for handling unpredictable data from APIs, ensuring your application can gracefully manage optional fields without crashing.
Real-world applications
Moving beyond theory and error-fixing, these techniques are the backbone of applications that process API data or manage user configuration files, especially when using vibe coding to rapidly prototype data processing tools.
Processing user preferences with json.loads()
When a user customizes their experience in an application, their settings are often sent as a JSON string, which you can easily parse into a usable dictionary with json.loads().
import json
# User preferences received from a client application
preferences_json = '{"theme": "dark", "fontSize": 14, "notifications": {"email": true, "push": false}}'
preferences = json.loads(preferences_json)
# Apply user settings to the application
theme_setting = preferences["theme"].capitalize()
notification_settings = [k for k, v in preferences["notifications"].items() if v]
print(f"Applying {theme_setting} theme with {preferences['fontSize']}px font")
print(f"Enabled notifications: {', '.join(notification_settings)}")
This code demonstrates how to work with data after converting it from a JSON string. Using json.loads() turns the string into a dictionary, making each piece of data easy to work with.
- Simple values like
themeandfontSizeare accessed directly with their keys. - A list comprehension efficiently filters the nested
notificationsdictionary, building a list of only the enabled notification types.
The final output shows how these extracted values can be used to apply settings within an application.
Analyzing weather data from API JSON strings
Parsing a JSON string from a weather API with json.loads() lets you quickly access and analyze nested data, such as current conditions and upcoming forecasts.
import json
# API response from a weather service
weather_json = '{"location":"New York","current":{"temp":22.5,"conditions":"Partly Cloudy","humidity":65},"forecast":[{"day":"Tomorrow","temp":24.8},{"day":"Wednesday","temp":20.1}]}'
weather_data = json.loads(weather_json)
# Extract and format current weather information
current = weather_data["current"]
forecast_temps = [day["temp"] for day in weather_data["forecast"]]
avg_forecast_temp = sum(forecast_temps) / len(forecast_temps)
print(f"Weather in {weather_data['location']}: {current['temp']}°C, {current['conditions']}")
print(f"Average forecast temperature: {avg_forecast_temp:.1f}°C")
This example shows how to handle a typical API response. After parsing the weather_json string with json.loads(), the data becomes a nested dictionary, making it easy to work with.
- You can access specific information, like the
currentconditions, by using dictionary keys. - A list comprehension efficiently pulls all
tempvalues from the nestedforecastlist.
Finally, the code calculates the average temperature from this new list and prints a formatted summary—a common pattern for processing complex data from web services, often requiring converting dictionaries to JSON for API responses.
Get started with Replit
Now, turn your knowledge into a real tool. Tell Replit Agent to "build a dashboard that parses weather API JSON" or "create a utility that converts a config file string to a dictionary."
Replit Agent handles the implementation. It writes the code, tests for errors, and deploys your app directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



