Python
String
Dictionary
Data Conversion
Programming

String to Dictionary in Python

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Converting a string to a Python dictionary depends on what the string actually contains. A JSON payload, a Python literal, and a query-string fragment look similar at a glance, but they require different parsers. The safest solution is to choose the parser that matches the input format exactly and avoid eval.

Parse JSON with json.loads

If the string comes from an API or serialized data interchange, it is probably JSON. In that case, use json.loads.

python
1import json
2
3text = '{"name": "Ada", "active": true, "score": 9}'
4data = json.loads(text)
5
6print(data)
7print(type(data))
8print(data["name"])

This is the correct path for standards-compliant JSON. Note that JSON uses true, false, and null, not Python's True, False, and None.

Parse Python Literal Syntax with ast.literal_eval

Sometimes the string is not JSON at all, but a Python dictionary literal copied from logs or internal code. In that case, json.loads fails because the syntax is different.

python
1import ast
2
3text = "{'name': 'Ada', 'active': True, 'score': 9}"
4data = ast.literal_eval(text)
5
6print(data)
7print(data["active"])

ast.literal_eval is much safer than eval because it only accepts Python literal structures such as strings, numbers, lists, tuples, dicts, booleans, and None.

Handle Query Strings and Key-Value Text Separately

If the source string looks like name=Ada&score=9, it is not a dictionary literal. It is a URL-encoded query string and should be parsed accordingly.

python
1from urllib.parse import parse_qs
2
3text = "name=Ada&score=9&score=10"
4data = parse_qs(text)
5
6print(data)

This returns lists of values because query-string keys may repeat. If you need a simple one-value-per-key dictionary, flatten it carefully:

python
flat = {key: values[0] for key, values in parse_qs(text).items()}
print(flat)

Choosing the right parser up front avoids a lot of brittle post-processing.

Never Use eval for This

eval can execute arbitrary code. That means an input string is no longer "data", it becomes executable source. For untrusted input, this is a security bug.

Bad pattern:

python
text = "__import__('os').system('echo dangerous')"
# eval(text)  # do not do this

Even for trusted internal tools, eval is almost always the wrong abstraction because it accepts far more than you need.

Validate the Resulting Structure

Parsing is only the first step. After converting the string, validate the shape and types before using the result. A string that parses successfully can still be missing required keys or contain the wrong value types.

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

This is especially important when the parsed dictionary drives downstream logic such as configuration or access control.

A practical parser should also fail clearly. If you expect JSON, raise a JSON-specific error instead of silently trying unrelated formats, because silent fallback hides bad inputs and makes debugging much harder later.

Common Pitfalls

  • Using json.loads on a Python literal string with single quotes and True.
  • Using ast.literal_eval on actual JSON and then wondering why booleans behave differently.
  • Reaching for eval because it appears to work on both formats.
  • Forgetting that query strings and JSON are different encodings.
  • Assuming that successful parsing means the data is semantically valid.

Summary

  • Use json.loads for JSON text.
  • Use ast.literal_eval for Python literal dictionary strings.
  • Use a dedicated parser such as parse_qs for query-string input.
  • Never use eval for string-to-dictionary conversion.
  • Validate keys and types after parsing so the dictionary is actually usable.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.