Python
Programming
Data Conversion
Dictionaries
String Manipulation

Convert a String representation of a Dictionary to a dictionary

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, turning a text value into a real dictionary is a common task when reading configuration, parsing API payloads, or handling stored data. The safest solution depends on what kind of string you actually have, because a Python literal string and a JSON string are not always the same thing.

Use json.loads for JSON Input

If the string is JSON, use json.loads. That is the standard parser for JSON objects and is the right choice for data coming from APIs, files, or message queues.

python
1import json
2
3text = '{"name": "John", "age": 30, "city": "New York"}'
4data = json.loads(text)
5
6print(data)
7print(data["name"])

This works only when the syntax is valid JSON. That means double quotes are required around strings and property names.

Use ast.literal_eval for Python Literal Syntax

Sometimes the string is not JSON. It may look like Python output with single quotes, True, or None. In those cases, ast.literal_eval is usually the safe parser.

python
1import ast
2
3text = "{'name': 'John', 'age': 30, 'city': 'New York'}"
4data = ast.literal_eval(text)
5
6print(data)
7print(type(data))

ast.literal_eval can parse Python literal structures such as dictionaries, lists, strings, numbers, booleans, and None. It is far safer than eval because it does not execute arbitrary expressions.

Do Not Use eval for Untrusted Strings

eval can appear to solve the problem quickly, but it is dangerous because it executes code, not just data.

python
text = "{'name': 'John'}"
# avoid this for real application code
# data = eval(text)

If the string comes from a user, file, network source, or database that you do not completely trust, eval creates a security risk. Even in internal tools, it is better to build the habit of using json.loads or ast.literal_eval instead.

Pick the Parser Based on the Source Format

A good rule is:

  • use json.loads for real JSON,
  • use ast.literal_eval for Python literal syntax,
  • preprocess malformed input only when you fully control the format.

That last point matters because many bugs come from trying to guess the format rather than confirming it. A string copied from Python logging output may need ast.literal_eval, while an HTTP response body almost certainly belongs to json.loads.

Validate the Result After Parsing

Parsing the string is only part of the job. You may still want to verify that the result is actually a dictionary and that required keys exist.

python
1import json
2
3text = '{"name": "John", "age": 30}'
4data = json.loads(text)
5
6if not isinstance(data, dict):
7    raise TypeError("Expected a dictionary")
8
9for key in ("name", "age"):
10    if key not in data:
11        raise KeyError(f"Missing key: {key}")

This makes later code safer and gives clearer failures than letting invalid structure leak deeper into the application.

Common Pitfalls

  • Using eval on data that should be treated as plain text input.
  • Calling json.loads on Python-style strings that use single quotes.
  • Calling ast.literal_eval on malformed text and assuming every parse error means the input was JSON.
  • Forgetting to check that the parsed result is actually a dictionary.
  • Trying to repair badly formatted input with ad hoc string replacements before understanding its real format.

Summary

  • Use json.loads when the string is valid JSON.
  • Use ast.literal_eval when the string is a Python literal representation.
  • Avoid eval for ordinary data parsing because it can execute code.
  • Choose the parser based on the actual source format, not on guesswork.
  • Validate the parsed structure before relying on specific dictionary keys.

Course illustration
Course illustration

All Rights Reserved.