To convert a dict to a string in Python, use json.dumps(d) when the text will be stored, sent to an API or read by another program, and str(d) for a quick, Python-style text you only want to print or log. For a custom format such as key=value pairs, join the items yourself. This guide compares these ways to convert a Python dictionary to a string, shows the formatting options, the two errors people hit most often, and how to turn the string back into a dict.
All examples were run with Python 3.12.5 in the Windows Command Prompt. Reference: json.dumps() and ast.literal_eval() in the Python docs.
str() vs json.dumps()
import json
order = {"id": 1042, "customer": "Anna", "paid": True, "items": ["pen", "notebook"]}
text1 = str(order) # Python syntax: single quotes, True
text2 = json.dumps(order) # JSON: double quotes, true
print(text1, type(text1))
print(text2, type(text2))
Output:
{'id': 1042, 'customer': 'Anna', 'paid': True, 'items': ['pen', 'notebook']} <class 'str'>
{"id": 1042, "customer": "Anna", "paid": true, "items": ["pen", "notebook"]} <class 'str'>
| str(d) | json.dumps(d) | |
|---|---|---|
| Quotes | Single quotes | Double quotes |
| True / None | True, None | true, null |
| Valid JSON? | No | Yes |
| Works for any value? | Yes | Only JSON types (unless you pass default=) |
| Convert back with | ast.literal_eval() | json.loads() |
| Use for | Printing, logging, debugging | Files, APIs, databases, other languages |
json.dumps() formatting options
import json
user = {"name": "José", "city": "São Paulo", "age": 31, "tags": ["admin", "beta"]}
print(json.dumps(user)) # non-ASCII escaped by default
print(json.dumps(user, ensure_ascii=False)) # keep the real characters
print(json.dumps(user, sort_keys=True, separators=(",", ":"))) # compact and ordered
print(json.dumps(user, indent=2, ensure_ascii=False)) # pretty, multi-line
Output:
{"name": "Jos\u00e9", "city": "S\u00e3o Paulo", "age": 31, "tags": ["admin", "beta"]}
{"name": "José", "city": "São Paulo", "age": 31, "tags": ["admin", "beta"]}
{"age":31,"city":"S\u00e3o Paulo","name":"Jos\u00e9","tags":["admin","beta"]}
{
"name": "José",
"city": "São Paulo",
"age": 31,
"tags": [
"admin",
"beta"
]
}
indent=2produces readable multi-line JSON.ensure_ascii=Falsekeeps characters like é and ã instead of\u00e9escapes.sort_keys=Truegives the same string for equal dictionaries, which helps when comparing or caching.separators=(",", ":")removes spaces for the smallest output.
TypeError: Object of type … is not JSON serializable
json.dumps() only understands dicts, lists, strings, numbers, booleans and None. Dates, Decimal, sets and your own classes raise a TypeError. Pass a default function that converts them:
import json
from datetime import date
from decimal import Decimal
invoice = {"number": "INV-7", "date": date(2025, 7, 4), "total": Decimal("149.90")}
try:
json.dumps(invoice)
except TypeError as e:
print("TypeError:", e)
print(json.dumps(invoice, default=str)) # convert anything unknown with str()
print(str(invoice)) # str() always works, but it is not JSON
Output:
TypeError: Object of type date is not JSON serializable
{"number": "INV-7", "date": "2025-07-04", "total": "149.90"}
{'number': 'INV-7', 'date': datetime.date(2025, 7, 4), 'total': Decimal('149.90')}
default=str turns unknown values into strings.Custom formats: key=value, keys only, values only
from urllib.parse import urlencode
settings = {"theme": "dark", "font_size": 14, "autosave": True}
print(", ".join(f"{k}={v}" for k, v in settings.items())) # key=value pairs
print("; ".join(f"{k}: {v}" for k, v in settings.items())) # any format you like
print(urlencode(settings)) # a URL query string
print(", ".join(settings)) # only the keys
print(", ".join(map(str, settings.values()))) # only the values
Output:
theme=dark, font_size=14, autosave=True
theme: dark; font_size: 14; autosave: True
theme=dark&font_size=14&autosave=True
theme, font_size, autosave
dark, 14, True
TypeError: sequence item 0: expected str instance
str.join() only joins strings, so joining numbers fails until you convert them:
scores = {"Anna": 91, "Ben": 78}
try:
print(", ".join(scores.values())) # the values are ints
except TypeError as e:
print("TypeError:", e)
print(", ".join(str(v) for v in scores.values())) # convert each value first
Output:
TypeError: sequence item 0: expected str instance, int found
91, 78
Convert the string back to a dictionary
Use the reverse of the function you used to create the string. Never use eval() on text you did not write, because it runs any code inside it:
import ast
import json
d = {"id": 7, "ok": True, "note": None}
s_json = json.dumps(d)
s_str = str(d)
print(json.loads(s_json) == d) # JSON text -> dict
print(ast.literal_eval(s_str) == d) # str() text -> dict, safely
try:
json.loads(s_str) # str() output is NOT valid JSON
except json.JSONDecodeError as e:
print("JSONDecodeError:", e)
Output:
True
True
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
json.loads() for JSON, ast.literal_eval() for str() output.More on this direction: convert a string to a dictionary in Python.
Nested dictionaries as a readable string
pprint.pformat() returns the same nicely wrapped text that pprint() prints:
from pprint import pformat
config = {"database": {"host": "db.example.com", "port": 5432, "options": {"ssl": True, "timeout": 30}},
"features": ["search", "export", "sharing"], "debug": False}
text = pformat(config, width=60) # a readable multi-line string
print(text)
Output:
{'database': {'host': 'db.example.com',
'options': {'ssl': True, 'timeout': 30},
'port': 5432},
'debug': False,
'features': ['search', 'export', 'sharing']}
Related dictionary and conversion tutorials:
- Convert a string to a dictionary in Python
- Convert a dictionary to JSON in Python
- Initialize a dictionary in Python
- Convert a string to float in Python
Frequently asked questions
How do I convert a dict to a string in Python?
Use json.dumps(d) for a JSON string or str(d) for Python-style text.
What is the difference between str(dict) and json.dumps(dict)?
str() uses Python syntax (single quotes, True, None) and is not valid JSON. json.dumps() produces JSON (double quotes, true, null) that other programs can read.
How do I convert a dictionary to a string without brackets?
Join the items: ", ".join(f"{k}={v}" for k, v in d.items()).
Why do I get TypeError: Object of type datetime is not JSON serializable?
JSON has no date type. Use json.dumps(d, default=str) or convert the value with isoformat() first.
How do I convert the string back to a dictionary?
json.loads(text) for JSON strings, or ast.literal_eval(text) for output of str().
How do I pretty-print a dict as a string?
json.dumps(d, indent=2) or pprint.pformat(d).
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn