Python | Dump a Dict to JSON File

A Dict in Python is a Data Structure which looks like {“Apple” : 10, “Banana”: 54, “Grapes”: 34} what if you want to store this dictionary into a JSON file.

Best method to do this is to use JSON Python Package do not worry you don’t need to install this explicitly as it’s already installed in your laptop or computer if you have installed Python Version 3 or above.

JSON Python Package have a function called dump which when passed a Dictionary Object and a output file stream will write content of Dictionary into the JSON file.

Below is the code for dumping a Python Dictionary to a JSON File.

import json
sample = {
    "Apple": 10,
    "Banana": 15,
    "Grapes": 49
    }
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

Save the above code in a File and when you run that file using Python filename.py on Terminal or Command Line then in the same directory as filename.py is in, a new file named result.json will be created which contain content of sample dictionary.

Dumping Dict to JSON

I hope that this article helped you to understand how to convert Dictionary Object in Python to a JSON File.

Comments to: Python | Dump a Dict to JSON File

Your email address will not be published.