Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

How to Convert a Dictionary to a String in Python

Use str() for readable Python display text, repr() for debugging, or json.dumps() when a dictionary must become JSON text for another system.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To convert a Python dictionary to ordinary display text, use str(data); for JSON text to exchange with an API, file, or another language, use json.dumps(data). Use repr(data) when you specifically want a debugging-oriented representation. These outputs are different formats, so choose according to how the string will be used.

Choose the right conversion

Need Use Result
Quick readable display str(data) A Python string representation intended to be fairly human-readable.
Debugging representation repr(data) A representation intended to be readable by the interpreter where possible.
JSON for an API or data exchange json.dumps(data) JSON-formatted text returned as a Python str.
Write JSON straight to a text file json.dump(data, file) JSON written to the file, rather than returned as a string.

Python’s tutorial distinguishes the functions this way: str() aims for a fairly human-readable representation, while repr() aims for one the interpreter can read where possible. See the Python input and output tutorial.

Convert a dictionary for display or debugging

Use str() for a quick string version of a dictionary:

person = {"name": "Ada", "age": 36}
text = str(person)
print(text)

The resulting string uses Python’s representation of the dictionary; it is not JSON. For debugging, you can request that representation explicitly with repr(person). Neither is the right choice when another system expects JSON.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert a dictionary to JSON text

Import Python’s standard-library json module and call json.dumps(). The function returns JSON text as a Python string:

import json

person = {"name": "Ada", "age": 36}
text = json.dumps(person)

For indented output that leaves non-ASCII characters visible in the resulting string, set indent and ensure_ascii:

text = json.dumps(person, indent=2, ensure_ascii=False)

By default, non-ASCII characters are escaped. You can also set sort_keys=True to sort output keys or use separators to control whitespace. The Python json module documentation describes dumps() as serializing an object to a JSON-formatted str.

Write JSON to a file

If you need a JSON file and do not need to keep the serialized text in a variable first, use json.dump() with a text file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import json

person = {"name": "Ada", "age": 36}
with open("person.json", "w", encoding="utf-8") as file:
    json.dump(person, file, indent=2, ensure_ascii=False)

The distinction is the destination: dumps() returns a string, while dump() writes to a file. The Python tutorial recommends UTF-8 for JSON files and demonstrates serialization and deserialization in its input and output examples.

What changes when a dictionary becomes JSON?

Dictionary keys become JSON strings

JSON object member names are strings. Python’s JSON encoder converts supported dictionary keys to strings, so the conversion may not preserve the original key types. For example, integer key 1 and string key "1" can both become the JSON member name "1". Such a collision means the encoded representation cannot retain both distinct keys as distinct names. Even without a collision, decoding JSON may produce a dictionary that does not compare equal to the original if it had non-string keys.

Some Python values need an explicit representation

JSON supports a defined set of Python values. A custom class or another unsupported value nested in a dictionary is not converted automatically; json.dumps() can raise TypeError. Decide how that value should be represented in JSON or supply an intentional custom encoder rather than assuming every Python object has a JSON equivalent.

Strict JSON and special floating-point values

By default, json.dumps() permits the non-standard values NaN, Infinity, and -Infinity, because allow_nan defaults to True. For strict JSON compliance, pass allow_nan=False; the encoder then raises ValueError if it encounters an out-of-range float. These options and conversion rules are documented in Python’s JSON encoder reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Parse the string using its actual format

For JSON text created with json.dumps(), use json.loads():

restored = json.loads(text)

ast.literal_eval() is for text containing Python literals or container displays, such as a dictionary representation; it is not a general expression evaluator. Python documents that it avoids executing code as eval() does, but warns that malicious or extreme input can still exhaust memory or stack space or consume excessive CPU. Use it only when the input is a Python literal from a trusted source and is appropriately limited. Never use eval() to parse untrusted text because it executes arbitrary code. For JSON input, use json.loads(). See the Python ast documentation for literal_eval() limitations.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.