How do you safely convert a string representation of a dictionary into a Python dict? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you safely convert a string representation of a dictionary into a Python dict?

message-square
0

Use json.loads(text) when the string is valid JSON (double-quoted keys/strings, true/false/null), or ast.literal_eval(text) when the string is formatted as a Python literal ({'key': True, 'count': None} with single quotes, tuples, or Python booleans)—never eval(), which executes arbitrary code and creates a critical security vulnerability.

Basic Example

import ast
import json

# 1. Recommended for JSON strings (double quotes, true/false/null):
json_str = '{"user": "alice", "active": true, "score": null}'
data_from_json = json.loads(json_str)
print(data_from_json)
# Output: {'user': 'alice', 'active': True, 'score': None}

# 2. Recommended for Python dict literal strings (single quotes, True/False/None):
py_literal_str = "{'user': 'alice', 'active': True, 'tags': ('admin', 'ops')}"
data_from_literal = ast.literal_eval(py_literal_str)
print(data_from_literal)
# Output: {'user': 'alice', 'active': True, 'tags': ('admin', 'ops')}

# 3. Validate that the parsed result is actually a dict (not a list, int, or tuple):
if not isinstance(data_from_literal, dict):
    raise TypeError(f"Expected dict, got {type(data_from_literal).__name__}")

Key Details & Edge Cases

  • Never use eval(text) on untrusted or external strings:
    • eval("__import__('os').system('rm -rf /')") executes arbitrary Python expressions immediately. Both json.loads() and ast.literal_eval() parse only static data structures without executing functions, attribute lookups, or imports.
  • ast.literal_eval() vs. json.loads() syntax differences:
    • json.loads() rejects single-quoted keys/strings ({'a': 1}), trailing commas ({"a": 1,}), Python True/False/None, and tuples (1, 2)—raising json.JSONDecodeError.
    • ast.literal_eval() rejects lowercase JSON true/false/null—raising ValueError: malformed node or string (because Python treats lowercase true as an unknown variable identifier, not a literal).
  • Always check isinstance(result, dict) after parsing:
    • Both json.loads("[1, 2, 3]") and ast.literal_eval("(1, 2)") succeed cleanly and return a list or tuple instead of a dict. Verify isinstance(result, dict) before calling .get() or key indexing.
  • Exceptions raised on malformed input (try / except):
    • json.loads() raises json.JSONDecodeError (a subclass of ValueError).
    • ast.literal_eval() raises ValueError, SyntaxError, TypeError, MemoryError, or RecursionError (for deeply nested brackets like "{" * 5000). Catch (ValueError, SyntaxError, TypeError) when parsing untrusted strings with ast.literal_eval().
  • Avoid naive .replace("'", '"') hacks to convert Python dicts into JSON:
    • Running py_str.replace("'", '"') corrupts strings containing apostrophes ("O'Reilly" becomes invalid JSON "O"Reilly") and fails on True/False/None. Use ast.literal_eval() directly on Python-formatted strings instead.

Comparison of String-to-Dictionary Parsing Methods in Python

Method Module Accepts Single Quotes & True/None? Accepts JSON true/false/null? Safe Against Code Execution? Best Used When
json.loads(s) (Fastest & Standard) json (stdlib) No Yes Yes Parsing API responses, config strings, or serialized JSON payloads.
ast.literal_eval(s) ast (stdlib) Yes No Yes Parsing Python str(my_dict) outputs, log dumps, or literal configs with True/None/tuples.
yaml.safe_load(s) pyyaml (3rd-party) Yes Yes Yes Parsing hybrid or unquoted YAML/JSON-like strings (slower; coerces yes/no to bools).
eval(s) (Unsafe) Built-in Yes No No (Remote Code Execution risk) Never—always replace with ast.literal_eval() or json.loads().