HOWTO · Python
How to Convert Dictionary to String in Python
Choose between a Python representation, JSON serialization, readable formatting, or a custom string when converting a Python dictionary.
On this page
A dictionary can become a string for display, logging, or data exchange, but these uses need different formats. str() gives Python’s representation, json.dumps() produces JSON text for interchange, pprint.pformat() creates readable formatting, and a loop lets you define a display format. These results are strings, but they do not all preserve the same types or promise that the original dictionary can be reconstructed.
Choose the right way to convert a dictionary to a string
Use str() when you need a quick Python-oriented representation, such as a debugging message. Use json.dumps() when another system expects JSON and your values fit JSON’s supported types. Choose pprint.pformat() to make nested Python data easier to inspect. Build a custom string when the output needs a specific layout, such as name: Alice, score: 9.
These are not interchangeable serialization formats. A custom display string and a str() result may be ambiguous or unsuitable for another program to parse. JSON supports objects, arrays, strings, numbers, booleans, and null; Python-only values such as tuples or sets need conversion or a different approach. Pickle is also not a string conversion: its serialization produces bytes, and loading pickle data from an untrusted source can execute harmful code.
Use str() for a Python representation
str(dictionary) is the concise option when a readable Python representation is enough. It includes dictionary braces and Python-style representations of keys and values. The exact formatting is intended for Python, not as a cross-language data contract; for example, Python uses True and None, while JSON uses true and null.
Run this example:
details = {"name": "Ada", "active": True}
text = str(details)
print(type(text).__name__)
print(text)
str
{'name': 'Ada', 'active': True}
Avoid assigning the dictionary to a variable named dict, because that shadows Python’s built-in type. Also remember that converting an object to text does not itself make that text reversible.
Serialize a dictionary as JSON with json.dumps()
For a standard data-interchange string, use json.dumps(). The matching json.loads() function parses JSON text back into Python values. JSON round-tripping preserves JSON-compatible data, but it does not retain every Python type: tuples become arrays and load as lists, and dictionary keys must be supported JSON key types. By default, non-ASCII characters are escaped; set ensure_ascii=False when you want them to appear directly. Use indent to make the JSON easier to read, or sort_keys=True for stable key ordering when that suits your use.
Run this example:
import json
record = {"name": "Ada", "score": 9}
text = json.dumps(record)
restored = json.loads(text)
print(text)
print(restored == record)
{"name": "Ada", "score": 9}
True
The value returned by json.dumps() is a string. If a dictionary contains values JSON cannot encode, provide a deliberate conversion strategy or choose a format designed for that data; do not assume JSON accepts every Python object.
Format a dictionary for readable output with pprint.pformat()
Use pprint.pformat() when you want a formatted string rather than printing directly to the console. It is useful for nested data because it can break long structures across lines. Its result remains a Python-oriented display representation, not JSON. You can tune width, indentation, depth, and compactness with its options; a depth limit abbreviates nested content, so the formatted result may not show all values.
Run this example:
import pprint
record = {"user": {"name": "Ada", "roles": ["author", "editor"]}}
text = pprint.pformat(record, sort_dicts=False)
print(type(text).__name__)
print(text)
str
{'user': {'name': 'Ada', 'roles': ['author', 'editor']}}
Use the returned string wherever needed, such as in a log message. In contrast, pprint.pprint() writes formatted text to a stream and is useful when you want to print rather than keep the result in a variable.
Build a custom string with a loop
A custom format gives control over separators and labels. A comprehension with str.join() avoids repeated string concatenation and makes it straightforward to omit a trailing delimiter. Decide how to handle values that may contain your chosen separator if another program will parse the result; a simple display format does not provide escaping rules automatically.
Run this example:
scores = {"Ada": 9, "Lin": 8}
text = ", ".join(f"{name}: {score}" for name, score in scores.items())
print(text)
Ada: 9, Lin: 8
This is suitable for a human-facing line. If the result must be exchanged or stored for later parsing, use JSON or define and implement a format with explicit quoting and escaping instead.
Convert a string back to a dictionary
Use json.loads() to parse a JSON string. It accepts JSON syntax, not arbitrary Python output from str(). For a Python literal string that you control, ast.literal_eval() can parse supported literal structures, including a dictionary, without evaluating arbitrary Python expressions. It is not a general parser and should not be used for untrusted, very large, or resource-intensive input. Validate the resulting type and contents for your application.
Run this example:
import ast
import json
json_text = '{"name": "Ada", "score": 9}'
python_text = "{'name': 'Ada', 'score': 9}"
print(json.loads(json_text))
print(ast.literal_eval(python_text))
{'name': 'Ada', 'score': 9}
{'name': 'Ada', 'score': 9}
Choose the parser that matches the format that produced the string. Neither parser can reliably recover a dictionary from an arbitrary custom display string unless that format has a corresponding parser and clearly defined rules.