string conversion
dictionary parsing
Python programming
data structures
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, converting a string that looks like a dictionary into a real dictionary depends on what format the string is actually in. The safe answer is usually ast.literal_eval for Python-literal input or json.loads for JSON input, while eval should generally be avoided.

Identify The Input Format First

These two strings look similar, but they are not the same format:

python
python_literal = "{'name': 'Ava', 'age': 30}"
json_text = '{"name": "Ava", "age": 30}'

The first is a Python literal style string. The second is JSON.

That distinction matters because the correct parser depends on it.

Use ast.literal_eval For Python Literal Input

If the string uses Python literal syntax, use ast.literal_eval:

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

This is the usual safe replacement for eval when the input contains only Python literals such as strings, numbers, lists, tuples, dictionaries, booleans, and None.

literal_eval does not execute arbitrary code, which is why it is much safer than eval.

Use json.loads For JSON

If the string is valid JSON, use the JSON parser instead:

python
1import json
2
3text = '{"name": "Ava", "age": 30}'
4data = json.loads(text)
5
6print(data)
7print(type(data))

This is the right choice when the data comes from web APIs, message queues, or configuration files that are meant to be JSON.

It is also usually faster and more interoperable when the source format is actually JSON.

Why eval Is Dangerous

You may see code like this:

python
text = "{'name': 'Ava', 'age': 30}"
data = eval(text)

It works for trusted toy examples, but it is dangerous because eval executes arbitrary Python code. If the string comes from a user, a file, or an external system, that is a security risk.

In real applications, choose:

  • 'ast.literal_eval for Python literal strings'
  • 'json.loads for JSON'

That rule prevents a large class of avoidable bugs and security problems.

Add Error Handling

Parsing can fail, so catch the appropriate exceptions:

python
1import ast
2
3text = "{'name': 'Ava', 'age': 30"
4
5try:
6    data = ast.literal_eval(text)
7except (SyntaxError, ValueError) as exc:
8    print(f"Could not parse dictionary text: {exc}")

For JSON:

python
1import json
2
3text = '{"name": "Ava", "age": 30'
4
5try:
6    data = json.loads(text)
7except json.JSONDecodeError as exc:
8    print(f"Invalid JSON: {exc}")

That makes failures easier to diagnose than letting the program crash deep in a data-processing pipeline.

Know The Limits

Not every string that "looks like a dictionary" should be parsed this way. If the text includes custom objects, function calls, or non-literal expressions, ast.literal_eval will reject it. That is usually a feature, not a bug.

If the source system can choose the format, JSON is often the better long-term contract because it is standardized and language-neutral.

If the source is specifically Python debug output or a Python-generated literal, ast.literal_eval is often the most practical tool.

Common Pitfalls

One common mistake is using json.loads on a Python-literal string that uses single quotes. JSON requires double quotes for strings and object keys.

Another issue is using ast.literal_eval on actual JSON and then assuming the two formats are interchangeable everywhere.

A third problem is reaching for eval because it "just works" on the first test case without considering the security cost.

Finally, parsing errors are often blamed on Python itself when the real problem is simply that the input string is not valid in the chosen format.

Summary

  • Use ast.literal_eval for strings that contain Python literal dictionary syntax.
  • Use json.loads for strings that contain valid JSON.
  • Avoid eval for untrusted or external input.
  • Add explicit error handling so malformed text fails clearly.
  • The right parser depends on the actual input format, not only on how similar the string looks to a dictionary.

Course illustration
Course illustration

All Rights Reserved.