How to Convert a Dictionary to a String in Python

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'>
Command Prompt output converting the same Python dictionary to a string with str() using single quotes and True, and json.dumps() using double quotes and true
Same dictionary, two different strings.
str(d)json.dumps(d)
QuotesSingle quotesDouble quotes
True / NoneTrue, Nonetrue, null
Valid JSON?NoYes
Works for any value?YesOnly JSON types (unless you pass default=)
Convert back withast.literal_eval()json.loads()
Use forPrinting, logging, debuggingFiles, 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=2 produces readable multi-line JSON.
  • ensure_ascii=False keeps characters like é and ã instead of \u00e9 escapes.
  • sort_keys=True gives 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')}
Command Prompt output of TypeError Object of type date is not JSON serializable and json.dumps with default=str converting the date and Decimal
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
Command Prompt output of a Python dictionary converted to key=value pairs, a custom separator format, a URL query string, keys only and values only
Joining the items gives you full control over the format.

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)
Command Prompt output showing json.loads and ast.literal_eval converting strings back to dictionaries and JSONDecodeError when loading str() output as JSON
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:

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).