How to Write a Dictionary to a JSON File in Python

Published by Brandon on

In this article we are going to take a look at how to write a dictionary to a JSON file in python. It’s actually really easy, and we are going to use build in modules to help!

Our Dictionary

Our dictionary is pretty simple, but of course you may have dictionaries that are much larger and more complex. Luckily for us, it doesn’t matter how large – the method will all be the same.

Here’s an example dictionary for a person named Jim. His data is in this dictionary, and we want that to be written to a JSON file to store for later, or send it off to another system.

data = {
    "Name": "Jim",
    "Age": 29,
    "Cats": ["Mr.Meow", "Whiskers"]
}

Above is our dictionary in the variable named data, now to just turn it into JSON.

The first thing we need to do is import the json module. Below that and where our dictionary resides, I’m going to use a with statement in python to open our file. I do this so we don’t have to worry about closing the file after it’s been written to.

In our with statement, I use the open function to open a file named testjson, and give it a mode of ‘w’ for write. This will rewrite the file each time vs ‘a’ for appending to the existing file. Then I give the opened file an alias of ‘f’.

import json

data = {
    "Name": "Jim",
    "Age": 29,
    "Cats": ["Mr.Meow", "Whiskers"]
}

# Open our file with write textmode
with open('./testjson.json', 'w') as f:

Lastly, I write this dictionary using the json.dump() method passing in the dictionary, and the filestream named ‘f’.

import json

data = {
    "Name": "Jim",
    "Age": 29,
    "Cats": ["Mr.Meow", "Whiskers"]
}

# Open our file with write 
with open('./testjson.json', 'w') as f:
    json.dump(data, f)

Thanks for checking out my article and feel free to also check out my YouTube Channel!

Categories: Python

0 Comments

Leave a Reply

Avatar placeholder

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