Mateen Kiani
Published on Thu Jul 31 2025·2 min read
Working with Python dicts often means you need to save them for later. JSON is a universal text format that many systems accept. But how do you turn your dict into JSON and write it to a file without fuss?
In this article, we'll walk you through the built-in json module, show you how to dump a dict to a file, handle errors, and keep your code clean and readable.
The json module is part of Python's standard library. It gives you two main functions: dump and dumps. Use dumps to get a JSON string from a dict. Use dump to write that string directly to a file.
import jsondata = {'name': 'Alice', 'age': 30, 'tags': ['developer', 'python']}json_string = json.dumps(data)print(json_string)
Tip: Use dumps when you need the JSON data in memory. Use dump when you want to write directly to a file.
To save your dict, open a file in write mode and use json.dump. This writes a compact JSON string to disk.
import jsondata = {'a': 1, 'b': 2}with open('data.json', 'w') as f:json.dump(data, f)
For more details on handling files, see our guide on writing JSON to file in Python.
By default, dump writes all data on one line. You can add indent and sort_keys to make it more readable.
import jsondata = {'b': 2, 'a': 1}with open('data.json', 'w') as f:json.dump(data, f, indent=4, sort_keys=True)
This will create a file that looks clean when you open it.
Working with I/O can fail. Wrap your code in try/except to catch common issues.
import jsontry:with open('data.json', 'w') as f:json.dump({'x': 1}, f)except IOError as e:print('File error:', e)except TypeError as e:print('Type error:', e)
Tip: A TypeError often means your dict has non-serializable objects. Convert them or use a custom encoder.
To read your JSON file as a Python dict, use json.load.
import jsonwith open('data.json', 'r') as f:data = json.load(f)print(type(data), data)
By following these steps, you can save and retrieve dict data safely. For a deeper look at converting dicts to JSON strings, check our json stringify guide.
Saving a Python dict as JSON is simple thanks to the built-in json module. Choose dump for files and dumps for strings. Handle errors and format your output. With this in your toolbox, you can move data between services, store settings, or log information in a standard, portable format.